iOS 设置view的层级关系

1.设置某view到最上层

// 初始化第一个view并添加到当前控制器的view上;

UIView *first = [[UIView alloc] initWithFrame:CGRectMake(30, 30, 100, 100)];

first.backgroundColor = [UIColor redColor];

[self.view addSubview:first];

// 初始化第二个view并添加到当前控制器的view上;

UIView *second = [[UIView alloc] initWithFrame:CGRectMake(50, 50, 100, 100)];

second.backgroundColor = [UIColor greenColor];

[self.view addSubview:second];

// 设置第一个view到最上层

[self.view bringSubviewToFront:first];

iOS 设置view的层级关系_第1张图片


2.设置某view到最下层

// 初始化第一个view并添加到当前控制器的view上;

UIView *first = [[UIView alloc] initWithFrame:CGRectMake(30, 30, 100, 100)];

first.backgroundColor = [UIColor redColor];

[self.view addSubview:first];

// 初始化第二个view并添加到当前控制器的view上;

UIView *second = [[UIView alloc] initWithFrame:CGRectMake(50, 50, 100, 100)];

second.backgroundColor = [UIColor greenColor];

[self.view addSubview:second];

// 初始化第三个view并添加到当前控制器的view上;

UIView *third = [[UIView alloc] initWithFrame:CGRectMake(70, 70, 100, 100)];

third.backgroundColor = [UIColor yellowColor];

[self.view addSubview:third];

[self.view sendSubviewToBack:second];

// 设置第二个view到最下层

[self.view sendSubviewToBack:second];


iOS 设置view的层级关系_第2张图片

3.设置某view到指定层

// 初始化第一个view并添加到当前控制器的view上;

UIView *first = [[UIView alloc] initWithFrame:CGRectMake(30, 30, 100, 100)];

first.backgroundColor = [UIColor redColor];

[self.view addSubview:first];

// 初始化第二个view并添加到当前控制器的view上;

UIView *second = [[UIView alloc] initWithFrame:CGRectMake(50, 50, 100, 100)];

second.backgroundColor = [UIColor greenColor];

[self.view addSubview:second];

// 初始化第三个view并添加到当前控制器的view上;

UIView *third = [[UIView alloc] initWithFrame:CGRectMake(30, 70, 100, 100)];

third.backgroundColor = [UIColor yellowColor];

[self.view addSubview:third];

// 设置第一个view在第一层;第二个在第三层;第三个在第四层;第四个在第二层

first.layer.zPosition = 1;  // red

second.layer.zPosition = 3; // green

third.layer.zPosition = 2;  // hello


iOS 设置view的层级关系_第3张图片

你可能感兴趣的:(iOS 设置view的层级关系)