此篇博文主要介绍的是UIView(视图)的一些常用用法,因为我们最常与视图打交道,之后很多控件也都是继承于UIView,可是说视图是基础控件,这里介绍了视图UIView的常用属性和方法,因为UIView是一些类的父类,之后有些具体的功能还需要其子类去实现.我们先对UIView做个大体的了解.
#import "RootViewController.h"
@interface RootViewController ()
@end
@implementation RootViewController
- (void)viewDidLoad {
[super viewDidLoad];
#pragma mark -- view视图的属性
// UIView(视图)代表屏幕上的一个矩形区域
// UIView继承于UIResponder,可以响应用户事件的
// 创建一个视图view
// 初始化一个view
UIView *myView = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
// 学习一个新控件,无非两种方法,1.进入API看看主要是干什么用的2.进入系统头文件中看看有什么方法和属性
// 下面介绍几个比较常用的UIView的属性
// frame(框架属性),CGRectMake构建一个frame
myView.frame = CGRectMake(200, 100, 200, 200);
// backgroundColor(背景属性)
myView.backgroundColor = [UIColor blackColor];
// center中心点属性,矩形view的中心点,是个点
myView.center = CGPointMake(200, 200);
// bounds界限属性,需要注意的是,bounds改变的是父视图的界限,带来的是子视图的变化,比如下面的10,10,100,100,父视图的0,0点就变成了10,10点,子视图是
根据父视图的0,0点坐标来添加的
myView.bounds = CGRectMake(10, 10, 100, 100);
// 视图的透明度属性,范围0-1,默认是1(不透明)
myView.alpha = 1;
// 视图的隐藏属性,BOOL值,YES隐藏.默认是NO不隐藏
myView.hidden = YES;
// 取出子视图的属性,返回值是数组
NSArray *subViews = self.view.subviews;
[myView release];
#pragma mark -- view视图方法
// 方法(主要是关于父视图,子视图的方法)
// 首先,你得先有父视图和子视图
UIView *aView = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
aView.backgroundColor = [UIColor blueColor];
[self.view addSubview:aView];
[aView release];
UIView *bView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
bView.backgroundColor = [UIColor yellowColor];
[aView addSubview:bView];
[bView release];
UIView *cView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
cView.backgroundColor = [UIColor redColor];
[aView addSubview:cView];
[cView release];
// 取出所有的子视图,先取出最下面的子视图,注意:子视图必须添加到父视图上那个才是父视图,越级是不可以的
NSArray *subviews = aView.subviews;
NSLog(@"%@",subviews);
// 把子视图插到相应的位置,注意:父视图去调用
[aView insertSubview:bView atIndex:0];
// 把视图添加到子视图的上面
[aView insertSubview:bView aboveSubview:cView];
// 把视图添加到子视图的下面
[aView insertSubview:bView belowSubview:cView];
// 把指定的视图放到最前面
[aView bringSubviewToFront:bView];
// 把指定的视图放到最后面
[aView sendSubviewToBack:bView];
// 按角标交换两个视图的位置
[aView exchangeSubviewAtIndex:0 withSubviewAtIndex:1];
// 删除父视图上的子视图,子视图去调用
[bView removeFromSuperview];
#pragma mark -- tag重点
aView.tag = 100;
// 这里的view即是aView,这里tag值用在取不到这个view的方法里,在外部取出,也可以用属性表示这个view
UIView *view = [self.view viewWithTag:100];
// 取出父视图
UIView *superView = cView.superview;
superView.backgroundColor = [UIColor blackColor];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
@end