frame和bounds的区别

我们先看看来自大众的解答:
frame: 该view在父view坐标系统中的位置和大小。(参照点是,父亲的坐标系统)
bounds:该view在本地坐标系统中的位置和大小。(参照点是,本地坐标系统,就相当于ViewB自己的坐标系统,以0,0点为起点)
看了只是在脑袋里一闪而过,好像并不明白啥时候用 frame, 啥时候用 bounds
我们来看看下面的代码:

-(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);
}

似乎就一目了然了。
下面做个 demo 演示下,
先在 self.view 加一个 子 View1 ,给背景色为灰色,给定一个 frame

 UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(50, 50, 100, 100)];
 view1.backgroundColor = [UIColor grayColor];
 [self.view addSubview:view1];
frame和bounds的区别_第1张图片
09B5D21B-91E0-4EA8-BC0A-DCEA87AB899F.png

接下来在 view1 上加 view2(红色)和 VIew3(绿色),view2的 frame 等于 View1 的 frame, View3 的 frame 等于View1的 bounds,对比下他们的位置。 代码如下:

  UIView *view2 = [[UIView alloc] initWithFrame:view1.frame];
    view2.backgroundColor = [UIColor redColor];
    [view1 addSubview:view2];
    
    UIView *view3 = [[UIView alloc] initWithFrame:view1.bounds];
    view3.backgroundColor = [UIColor greenColor];
    [view1 addSubview:view3];

运行结果如下:


frame和bounds的区别_第2张图片
DE9501F6-9804-4F4D-9634-3AD2EA3C850D.png

结果显示:

等于 bounds 的那个 View(绿色)完全覆盖了父 视图(View1),而等于 frame 的那个 View 则是在父视图(View1) 中向右向下偏移了各50, 所以在开发中如果你需要在一个子 View 上覆盖一个大小位置一样的子子 View,让子 子 View 的 frame 等于子 View 的 bounds 就可以。

你可能感兴趣的:(frame和bounds的区别)