素材巴巴 > 程序开发 >

iOS项目开发实战——UIView的层级关系

程序开发 2023-09-03 13:42:03

      iOS项目开发中,View其实是有层级关系的,这种层级关系可以理解为等级。简单的描述就是:后加入的View等级较高,会把先加入的View盖住。如果父视图等级较低,那么它的子视图等级也较低。具体代码实现如下:

#import "ViewController.h"@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad {[super viewDidLoad];//view1的层级最低;UIView *view1 = [[UIView alloc] init];view1.frame = CGRectMake(50, 50, 200, 200);view1.backgroundColor = [UIColor yellowColor];[self.view addSubview:view1];//view2的层级第三;//先加入的View会被后来加入的View盖住;//坐标是根据父视图的位置来设置的,不会跨层;UIView *view2 = [[UIView alloc] init];view2.frame = CGRectMake(20, 20, 100, 100);view2.backgroundColor = [UIColor redColor];[view1 addSubview:view2];//view3的层级最高;UIView *view3 = [[UIView alloc] init];view3.frame = CGRectMake(20, 80, 100, 100);view3.backgroundColor = [UIColor whiteColor];[view1 addSubview:view3];//view22的层级第二;子视图的层级比父视图高;//虽然view22是后面加入的,但是本身父视图view2的层级比view3的层级低,所以子视图view22的层级也比view3的层级低,会被view3压在下面;UIView *view22 = [[UIView alloc] init];view22.frame = CGRectMake(20, 50, 100, 100);view22.backgroundColor = [UIColor purpleColor];[view2 addSubview:view22];}@end
 

效果如下:


github主页:https://github.com/chenyufeng1991  。欢迎大家访问!


标签:

素材巴巴 Copyright © 2013-2021 http://www.sucaibaba.com/. Some Rights Reserved. 备案号:备案中。