什么是UIWindow
1.管理和协调应用程序的显示
2.UIWindow类是UIView的子类,可以看作是特殊的UIView
3.一般应用程序只有一个UIWindow对象。
UIWidow对象有两种方式创建:
1.Xcode 5之前工程中有EmptyApplication模板,需要代码创 建UIWindow对象。
2.从Xcode 6开始苹果取消EmptyApplication模板,通常使 用SingleViewApplication模板,使用StoryBoard自动创建 UIWindow对象,不需要使用代码。
下面开始用代码创建UIWIndow:
_window = [[UIWindow alloc]initWithFrame:[[UIScreen mainScreen]bounds]]; //创建一个windows,并使其铺满屏幕
[_window setBackgroundColor:[UIColor redColor]];
[_window setBackgroundColor:[UIColor colorWithRed:28/255. green:173/255. blue:253/255. alpha:1.]];
创建一个视图控制器
ViewController *view = [[ViewController alloc]init];
//绘制window的根视图控制器
[_window setRootViewController:view];
//使window显示
[_window makeKeyAndVisible];
创建控件View:
第一步,申请内存空间并初始化
UIView *view1 = [[UIView alloc]init];
第二步,设置坐标大小
[view1 setFrame:CGRectMake(0, 0, 200, 200)];
第三步,设置控件属性
[view1 setBackgroundColor:[UIColor redColor]];
Center实现方法:
[view1 setCenter:self.window.center];
//中心点,求出高再/2, 求出宽再/2
//[view1 setCenter:CGPointMake([UIScreen mainScreen].bounds.size.width / 2, [UIScreen mainScreen].bounds.size.height /2)];
Ta'g实现方法:
[view1 setTag:1];
第四步,添加子视图
[self.window addSubview:view1];
[view1 release];
NSLog(@"%@",view1.superview);
NSLog(@"%@",self.window.subviews); //获取所有子视图
在指定的视图下面添加子视图
UIView *newView = [self.window viewWithTag:1];
[newView setBackgroundColor:[UIColor magentaColor]];
添加子视图
UIView *view2 = [[UIView alloc]initWithFrame:CGRectMake(100, 100, 200, 200)];
[view2 setBackgroundColor:[UIColor yellowColor]];
[self.window addSubview:view2];
UIView *view3 = [[UIView alloc]initWithFrame:CGRectMake(200, 200, 200, 200)];
[view3 setBackgroundColor:[UIColor greenColor]];
[self.window addSubview:view3];
在指定的index处插入子视图
UIView *view4 = [[UIView alloc]initWithFrame:CGRectMake(50, 50, 200, 200)];
[view4 setBackgroundColor:[UIColor cyanColor]];
[self.window insertSubview:view4 atIndex:2];
在指定的视图上面添加子视图
UIView *view5 = [[UIView alloc]initWithFrame:CGRectMake(150, 150, 200, 200)];
[view5 setBackgroundColor:[UIColor redColor]];
[self.window insertSubview:view5 aboveSubview:view2];
把指定的子视图移动到最前面(层次变动,位置不变)
[self.window bringSubviewToFront:view2];
把指定的子视图移动到最后面
[self.window sendSubviewToBack:view2];
交换两个指定索引位置的子视图
[self.window exchangeSubviewAtIndex:1 withSubviewAtIndex:2];
把子视图从父视图上移除
[view2 removeFromSuperview];