您的位置:首页 > 移动开发 > IOS开发

三言两语frame&bounds

2016-03-21 15:05 465 查看
简单说明一下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)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  frame bounds view iOS