部分内容转载自:http://blog.csdn.net/mad1989/article/details/8711697
看一段Demo:
UIView *view1 = [[UIViewalloc]
initWithFrame:CGRectMake(20,20,
280,250)];
[view1 setBounds:CGRectMake(-20, -20,500,
500)];
view1.backgroundColor = [UIColorredColor];
[self.viewaddSubview:view1];//添加到self.view
NSLog(@"view1 frame:%@========view1 bounds:%@======view1 center:%@",NSStringFromCGRect(view1.frame),NSStringFromCGRect(view1.bounds),NSStringFromCGPoint(view1.center));
[view1 setFrame:CGRectMake(50,50,
200,200)];
NSLog(@"again===view1 frame:%@========view1 bounds:%@======view1 center:%@",NSStringFromCGRect(view1.frame),NSStringFromCGRect(view1.bounds),NSStringFromCGPoint(view1.center));
UIView *view2 = [[UIViewalloc]
initWithFrame:CGRectMake(0,0,
100,100)];
view2.backgroundColor = [UIColoryellowColor];
[view1 addSubview:view2];//添加到view1上,[此时view1坐标系左上角起点为(-20,-20)]
NSLog(@"view2 frame:%@========view2 bounds:%@======view2 center:%@",NSStringFromCGRect(view2.frame),NSStringFromCGRect(view2.bounds),NSStringFromCGPoint(view2.center));
再看下log日志:
2015-02-13 14:44:21.767 [37262:272312] view1 frame:{{-90, -105}, {500, 500}}========view1 bounds:{{-20, -20}, {500, 500}}======view1 center:{160, 145}
2015-02-13 14:44:21.768 [37262:272312] again===view1 frame:{{50, 50}, {200, 200}}========view1 bounds:{{-20, -20}, {200, 200}}======view1 center:{150, 150}
2015-02-13 14:44:21.768 [37262:272312] view2 frame:{{0, 0}, {100, 100}}========view2 bounds:{{0, 0}, {100, 100}}======view2 center:{50, 50}
可以得出这几个结论:
1.bounds和frame的size的width和height都一样
2.若frame改变,则bounds和center都改变
3.若bounds改变,则frame改变,但是center不变
4.bounds会影响当前view的subview的位置,但不会影响当前view的位置。
以上的结论有一个前提,就是view的transform属性的值是恒等变换的,(也就是CGAffineTransformIsIdentity()的值是YES)。
如果transform属性的值不是恒等变换的,那么frame属性的值就是为定义的,必须被忽略。在设置变换属性之后,要使用bounds和center属性来获取视图的位置和大小。
这种情况往往发生在对view的属性做transform变换之后。
以一个Demo来举例:
UIView *testView = [[UIView
alloc] initWithFrame:CGRectMake(0,
0, 100,
100)];
testView.backgroundColor = [UIColor
greenColor];
[self.view
addSubview:testView];
testView.transform =
CGAffineTransformMakeScale(0.5,
0.5);
NSLog(@"testView frame:%@========testView bounds:%@======testView center:%@",NSStringFromCGRect(testView.frame),NSStringFromCGRect(testView.bounds),NSStringFromCGPoint(testView.center));
打印的log日志如下:
2015-02-13 16:13:09.791 [39158:326284] testView frame:{{25, 25}, {50, 50}}========testView bounds:{{0, 0}, {100, 100}}======testView center:{50, 50}
此时
CGAffineTransformIsIdentity(testView.transform)为NO。
这就是一个不恒等变换,此时的位置要根据bounds和center来计算得出。设置
testView.transform =
CGAffineTransformIdentity;可以复原testView的位置,也就是frame为(0,0,100,100)。