UIView *test_View = [[UIView alloc] initWithFrame:CGRectMake(40, 40, 100, 100)];
test_View.backgroundColor = [UIColor redColor];
[self.view addSubview:test_View];
NSLog(@"frame:%.2f %.2f %.2f %.2f",test_View.frame.origin.x,test_View.frame.origin.y,test_View.frame.size.width,test_View.frame.size.height);
NSLog(@"bounds:%.2f %.2f %.2f %.2f",test_View.bounds.origin.x,test_View.bounds.origin.y,test_View.bounds.size.width,test_View.bounds.size.height);
NSLog(@"center:%.2f %.2f",test_View.center.x,test_View.center.y);
输出:
2018-03-20 15:40:41.061000+0800 frame_bounds_center[3431:215798] frame:40.00 40.00 100.00 100.00
2018-03-20 15:40:41.061125+0800 frame_bounds_center[3431:215798] bounds:0.00 0.00 100.00 100.00
2018-03-20 15:40:41.061218+0800 frame_bounds_center[3431:215798] center:90.00 90.00
frame
frame属性代表的是当前视图的的位置和大小,没有设置,当前视图你是无法看见的,因此在在初始化视图时要指定视图的frame:
-(id)initWithFrame:(CGRect)frame;
- frame中的位置是以父视图的坐标系为标准来确定当前视图的位置
- 修改frame的位置,当前视图的位置也会跟着改变
- 修改frame的大小,当前视图的大小也会随之改变
center
center就是视图中心点在父视图中的位置坐标
bounds
bounds指的是视图在自己坐标系中的位置与大小
- 更改bounds中位置对当前视图没有影响,但会改变当前视图坐标系的原点位置,相对于子视图来说,当前视图的原点已经不是(0,0)了,而是修改以后的值
UIView *test_View = [[UIView alloc] initWithFrame:CGRectMake(40, 40, 100, 100)];
test_View.backgroundColor = [UIColor redColor];
[self.view addSubview:test_View];
UIView *small_View = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
small_View.backgroundColor = [UIColor orangeColor];
[test_View addSubview:small_View];
CGRect bounds = test_View.bounds;
bounds.origin.x = -20;
test_View.bounds = bounds;
总结
当View的frame修改时
1.更改origin,对bounds没有影响,View的center会被改变
2.更改size,bounds的width和height会跟修改后的frame.size一样,View的center会被修改
当View的bounds修改时
1.更改origin,frame不会改变,View的center不会改变
2.更改size frame.size会与修改后的bounds.size一样,View的center不会改变