UI基础(二)-图层
1、clipsToBounds:裁切边境(把超出的部分剪切掉)
bgView.clipsToBounds = YES;
2、removeFromSuperview:从父视图移除视图
[view removeFromSuperview];
注:
1)子视图依赖于父视图,如果父视图位置发生改变,子视图位置也会发生改变,因为frame是根据它的父视图来定义位置信息的。
2)如果移除父视图,父视图上面的子视图也都会被移除。
3)操作两个图层的图层关系时,两个视图必须在同一个父视图上,如果两个视图不是同一个父视图,那他们两个就没有任何关系。
3、bringSubviewToFront:把某个视图放到父视图的最上面
[self.window bringSubviewToFront:bgView];
4、把一个视图放到与它相邻视图的最下面
[self.window sendSubviewToBack:bgView];
5、把一个子视图放到另一个子视图的下面
[self.window insertSubview:view1 belowSubview:view];
6、把一个子视图放到另一个子视图的上面
[self.window insertSubview:view aboveSubview:view1];
7、交换父视图上面的两个视图的图层位置
[self.window exchangeSubviewAtIndex:0 withSubviewAtIndex:2];
注:往同一个父视图上添加子视图的时候,系统会自动记录一个Index,只要添加一个子视图,就会增加1,从0开始。
8、插入一个视图到指定的图层
[self.window insertSubview:view1 atIndex:0];
9、定时
[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(run) userInfo:nil repeats:YES];
10、延时
[self performSelector:@selector(run) withObject:nil afterDelay:3];
- (void)run{
UIView *bgView = [self.window viewWithTag:200];
int x = arc4random()%300;
int y = arc4random()%600;
bgView.center = CGPointMake(x, y);
}
例:可变霓虹灯练习
#import "AppDelegate.h"
@interface AppDelegate ()
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
colorList = @[[UIColor whiteColor], [UIColor blueColor], [UIColor magentaColor], [UIColor yellowColor], [UIColor grayColor], [UIColor greenColor], [UIColor orangeColor], [UIColor darkGrayColor], [UIColor lightGrayColor], [UIColor cyanColor], [UIColor redColor], [UIColor purpleColor], [UIColor brownColor]];
self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 200, 300)];
view.backgroundColor = [UIColor brownColor];
view.tag = 100;
[self.window addSubview:view];
for (int i = 0; i < 18; i ++) {
int num = arc4random()%240;
int num1 = arc4random()%colorList.count;
UIView *view1 = [[UIView alloc]initWithFrame:CGRectMake((10 + 1.2) * i, 0, 10, num + 40)];
view1.backgroundColor = colorList[num1];
view1.tag = 200 + i;
[view addSubview:view1];
}
[self.window makeKeyAndVisible];
[NSTimer scheduledTimerWithTimeInterval:0.7 target:self selector:@selector(change) userInfo:nil repeats:YES];
return YES;
}
- (void)change{
for (int i = 0; i < 18; i ++) {
int num = arc4random()%240;
int num1 = arc4random()%colorList.count;
UIView *theView = [self.window viewWithTag:200 + i];
theView.backgroundColor = colorList[num1];
theView.frame = CGRectMake((10 + 1.2) * i, 0, 10, num + 40);
UIView *view2 = [self.window viewWithTag:100];
view2.backgroundColor = colorList[arc4random()%colorList.count];
view2.frame = CGRectMake(arc4random()%175, arc4random()%367, 200, 300);
}
}