uiview 是视图,即显示在手机屏幕,能看得到的东西。
一切显示的视图控件都是uiview的子类,uiview有的属性,其子类也有。
视图在手机屏幕上的显示,在满足几个条件:
1 必须实例化
2 设置frame,即坐标(x坐标、y坐标),大小(长、宽),注意frame是针对其所在的父视图来设置的
3 添加到父视图,即实现 addSubview 方法
4 注意其隐藏属性hidden设置为NO(默认为NO,即可见),以及透明度alpha设置为1.0(默认为1.0,即不透明)
- // 实例化视图
- UIView *view01 = [[UIView alloc] init];
- // 设置背景颜色
- view01.backgroundColor = [UIColor redColor];
- // 坐标大小设置
- view01.frame = CGRectMake(10.0, 50.0, 100.0, 100.0);
- // 隐藏属性,NO为显示,YES为隐藏,默认为NO
- view01.hidden = NO;
- // 透明度,取值范围0.0~1.0,默认为1.0
- view01.alpha = 1.0;
- // 视图tag值,相当房号,注意:tag值的设置通常都设置成大于1000,避免与系统控件的tag值重复,造成冲突
- view01.tag = 1000;
- // 添加到父视图,即self.view父视图,添加到父视图才可见,否则不可见
- [self.view addSubview:view01];
- // 从父视图删除,删除后不可见
- // [view01 removeFromSuperview];
- // layer图层属性
- // 圆角属性
- view01.layer.cornerRadius = 10.0;
- // 边框大小
- view01.layer.borderWidth = 5.0;
- // 边框颜色
- view01.layer.borderColor = [UIColor yellowColor].CGColor;
- // 图层遮罩(避免有时候圆角属性设置不成功)
- view01.layer.masksToBounds = YES;
- // 其他属性
- // center中心坐标
- view01.center = CGPointMake(self.view.center.x, view01.center.y); // 水平居中
- // view01.center = CGPointMake(view01.center.x, self.view.center.y); // 垂直居中
- // view01.center = self.view.center; // 父视图的正中间
- // superview父视图
- UIView *superView = view01.superview;
- superView.backgroundColor = [UIColor brownColor];
- NSLog(@"superView %@", superView);
- // bounds大小,视图的大小,忽略坐标,即相对于视图自己来设置的
- CGRect bounds = view01.bounds;
- NSLog(@"bounds %@", NSStringFromCGRect(bounds));
- // 子视图数组
- NSArray *viewArray = self.view.subviews;
- NSLog(@"viewArray %@", viewArray);
- UIView *view02 = [[UIView alloc] initWithFrame:CGRectMake(20.0, 200.0, 200.0, 200.0)];
- view02.backgroundColor = [UIColor yellowColor];
- [self.view addSubview:view02];
- view02.tag = 1001;
- UIView *view03 = [[UIView alloc] initWithFrame:CGRectMake(10.0, 10.0, 60.0, 60.0)];
- view03.backgroundColor = [UIColor greenColor];
- [view02 addSubview:view03];
- view03.tag = 1003;
- UIView *view04 = [[UIView alloc] initWithFrame:CGRectMake(10.0, 10.0, 80.0, 80.0)];
- view04.backgroundColor = [UIColor purpleColor];
- [view02 addSubview:view04];
- // 改变两个视图在父视图的位置
- [view02 exchangeSubviewAtIndex:0 withSubviewAtIndex:1];
- UIView *view05 = [[UIView alloc] initWithFrame:CGRectMake(20.0, 20.0, 100.0, 100.0)];
- view05.backgroundColor = [UIColor redColor];
- // 插入子视图到指定视图之上
- [view02 insertSubview:view05 aboveSubview:view04];
- // 把指定的子视图放在父视图的最后一层
- [view02 sendSubviewToBack:view05];
- // 把指定的子视图放在父视图的最前面
- [view02 bringSubviewToFront:view05];
- // 简单动画
- // 方法1
- [UIView beginAnimations:@"view001" context:nil]; // 动画开始标识
- [UIView setAnimationDuration:3.0]; // 动画时间
- view01.frame = CGRectMake(10.0, CGRectGetHeight(self.view.bounds) - 50.0, 100.0, 100.0); // 动画效果
- [UIView commitAnimations]; // 开始动画
- // 方法2
- [UIView animateWithDuration:3.0 animations:^{
- view01.frame = CGRectMake(10.0, self.view.center.y, 100.0, 100.0); // 动画效果
- }];