三言两语frame&bounds

来源:互联网 发布:淘宝怎么账号登陆 编辑:程序博客网 时间:2024/06/07 05:12

简单说明一下ios view的frame属性和bounds属性,直接看代码。

- (void)viewDidLoad {    [super viewDidLoad];    UIView *centerView =        [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];    centerView.backgroundColor = [UIColor redColor];    centerView.center = self.view.center;    [self.view addSubview:centerView];//    centerView.bounds = CGRectMake(0, 0, 200, 200);    UIView *subView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];    subView.backgroundColor = [UIColor blackColor];    [centerView addSubview:subView];}

效果:


如果我们修改view的bounds属性:
- (void)viewDidLoad {    [super viewDidLoad];    UIView *centerView =        [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];    centerView.backgroundColor = [UIColor redColor];    centerView.center = self.view.center;    [self.view addSubview:centerView];    //修改centerView的bounds属性    centerView.bounds = CGRectMake(10, 10, 300, 400);    UIView *subView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];    subView.backgroundColor = [UIColor blackColor];    [centerView addSubview:subView];}

效果:


我们可以看到,红色的centerView变大了,但是相对于父视图的位置没有发生变化,因为我们没有改变他的frame属性,黑色的subView大小没有变化,但是相对于centerView的位置发生了变化。


解释:

frame属性中的(x, y, width, height),x和y都是说这个视图相对于父视图的位置,后者表示本身的大小;

bounds属性中的x和y,表示的是这个视图本身所拥有的坐标系统的原点位置,默认在视图的左上角,即(0, 0),我们修改为(10, 10),这时候会把他的自身坐标系统像左上方移动10,但是视图本身的位置并不会发生变化,仅仅是它所拥有的坐标系统原点发生了变化,因为很色subView是参照这个坐标系的,因此黑色的subView的原点相对红色视图左上角的点,偏移了(10, 10)

1 0
原创粉丝点击