三言两语frame&bounds

简单说明一下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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值