view中frame和bounds的区别

view的bounds默认的都为(0,0,self.frame.size.width,self.frame.size.height)
view的位置是由view.frame决定的,而view.bounds决定的是其内子视图的原点。写个例子就明白了

 1 - (void)viewDidLoad {
 2     [super viewDidLoad];
 3     self.view.backgroundColor = [UIColor lightGrayColor];
 4     [self setupAllBack];
 5 }
 6 
 7 -(void)setupAllBack{
 8     UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(20, 20, 280, 250)];
 9     view1.bounds = CGRectMake(-20, -20, 280, 250);
10     view1.backgroundColor = [UIColor redColor];
11     [self.view addSubview:view1];//添加到self.view
12     NSLog(@"view1 frame:%@========view1 bounds:%@",NSStringFromCGRect(view1.frame),NSStringFromCGRect(view1.bounds));
13     
14     UIView *view2 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
15     view2.backgroundColor = [UIColor brownColor];
16     [view1 addSubview:view2];//添加到view1上,此时view1坐标系左上角起点为(-20,-20)
17     NSLog(@"view2 frame:%@========view2 bounds:%@",NSStringFromCGRect(view2.frame),NSStringFromCGRect(view2.bounds));
18 }

打印结果为:
2015-07-21 13:23:20.941 Demo-frame和bounds区别[2147:87996] view1 frame:{{20, 20}, {280, 250}}========view1 bounds:{{-20, -20}, {280, 250}}
2015-07-21 13:23:20.942 Demo-frame和bounds区别[2147:87996] view2 frame:{{0, 0}, {100, 100}}========view2 bounds:{{0, 0}, {100, 100}}

上边demo的图示如下:

因为view2是在view1上的原点(0,0)处开始绘制的,而view1的原点为(-20,-20),所以view2要向下、向右分别移动20单位,才符合view2的要求。

原文地址:https://www.cnblogs.com/Apologize/p/4680508.html