bounds和frame的区别

2018-04-12  本文已影响0人  敌敌味丶
//底部view   灰色
UIView *superview = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 200, 200)];
superview.backgroundColor = [UIColor grayColor];
[self.view addSubview:superview]; 

//bounds   红色
UIView *view = [[UIView alloc] init];
view.backgroundColor = [UIColor redColor];
view.bounds = CGRectMake(0, 0, 100, 50);
[superview addSubview:view];

//frame    黄色
UIView *view2 = [[UIView alloc] init];
view2.backgroundColor = [UIColor yellowColor];
view2.frame = CGRectMake(10, 50, 100, 100);
[superview addSubview:view2];
设置bounds的为红色view的打印

此情况下,在view.bounds = CGRectMake(x, y, W, H)中,无论x、y怎么设置最后打印出的结果都是(-W/2, -H/2, W, H).

若取用同级的view的bounds来作为自己的frame,坐标就直接为0:
//bounds   蓝色
UIView *view3 = [[UIView alloc] init];
view3.backgroundColor = [UIColor blueColor];
view3.frame = view2.bounds;
[superview addSubview:view3];
蓝色的view的打印
若在初始化时先使用bounds,再修改所使用的view的bounds的坐标,此时的view的坐标就会相对参照的view向反方向移位。
//参照的 bounds    绿色
UIView *view4 = [[UIView alloc] initWithFrame:superview.bounds];
view4.backgroundColor = [UIColor greenColor];
superview.bounds = CGRectMake(60, 10, 200, 200);
[superview addSubview:view4];
绿色的view

总结:

上一篇下一篇

猜你喜欢

热点阅读