layout: post title: “iOS view 的 frame 和 bounds 之区别” date: 2015-06-29 09:59:10 +0800 comments: true keywords: ios

categories: ios

img

一、首先列一下公认的资料:

先看到下面的代码你肯定就明白了一些:

-(CGRect)frame{
    return CGRectMake(self.frame.origin.x,self.frame.origin.y,self.frame.size.width,self.frame.size.height);
}
-(CGRect)bounds{
    return CGRectMake(0,0,self.frame.size.width,self.frame.size.height);
}

很明显,bounds 的原点是(0,0)点(就是 view 本身的坐标系统,默认永远都是0,0点,除非认为 setbounds),而 frame 的原点却是任意的(相对于父视图中的坐标位置)。

再来看张图就明白了,

img

每个 view 都有一个本地坐标系统。这个坐标系统作用比较重要,比如触 摸的回调函数中的 UITouch 里面的 > 坐标值都是参照这个本地坐标系统的坐标。当然 bounds 这个属性也是参照这个本地坐标系统来的。其实本地 坐标系统的关键就是要知道的它的原点(0,0)在什么位置(这个位置又是相对于上层的 view 的本地坐标系统而言的,当然最上面的一层 view 就是 window 它的本地坐标系统原点就是屏幕的左上角了)。通过修改 view 的 bounds 属性可以修改本地坐标系统的原点位置。

所以,bounds 影响到子 view 的位置和大小。

二、demo演示:

UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(20, 20, 280, 250)];  
[view1 setBounds:CGRectMake(-20, -20, 280, 250)];  
view1.backgroundColor = [UIColor redColor];  
[self.view addSubview:view1];//添加到self.view  
NSLog(@"view1 frame:%@========view1 bounds:%@",NSStringFromCGRect(view1.frame),NSStringFromCGRect(view1.bounds));  

UIView *view2 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];  
view2.backgroundColor = [UIColor yellowColor];  
[view1 addSubview:view2];//添加到view1上,[此时view1坐标系左上角起点为(-20,-20)]  
NSLog(@"view2 frame:%@========view2 bounds:%@",NSStringFromCGRect(view2.frame),NSStringFromCGRect(view2.bounds));

img

img

(log输出日志表明,每个新的 view 默认的 bounds 其实都是(0,0)) img