一、概述
UIView中定义了三个属性:frame, center, bounds。
@property (nonatomic, strong) CGRect frame;
@property (nonatomic, strong) CGRect bounds;
@property (nonatomic, strong) CGPoint center;
苹果官方对于这三个属性的说明如下:
frame:描述当前视图在父视图中位置和大小。如: initWithFrame(10, 10, 200, 200);
bounds:描述当前视图在其自己所在的坐标系中的位置和大小。如:[view setBounds:CGRectMake(0, 0, 50, 50)];
center:描述当前视图在其父视图中的位置。
二、详解
对于以下代码
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.window.backgroundColor = [UIColor whiteColor];
UIView* testView = [[UIView alloc] initWithFrame:CGRectMake(50, 50, 100, 100)];
testView.backgroundColor = [UIColor redColor];
[self.window addSubview:testView];
[self.window makeKeyAndVisible];
return YES;
}
输出testView的frame、bounds、center属性如下:
Frame: (50, 50, 100, 100)
Bounds: (0, 0, 100, 100)
Center: (100, 100)
默认情况下,当视图创建后,其坐标原点(0, 0)位于其左上角,这里对于testView而言,其父视图的坐标原点位于显示屏的左上角,因此,设置frame属性后,testView的坐标原点位于其父视图(即self.window)所在坐标系的(50,50)处,其尺寸大小为width=100,height=100,因此,其center属性的值也为(100, 100) (在父视图坐标系中的位置)。如下图所示:
通常情况下,较少使用bounds属性来设置视图的位置和尺寸,一般使用frame设置视图的位置和尺寸,center移动视图的位置。而且,对视图的旋转、缩放等操作也是基于center属性的。
下面,我们在testView视图上添加一个子视图,来看看使用frame、bounds和center属性对视图位置和尺寸的影响。
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.window.backgroundColor = [UIColor whiteColor];
UIView* testView = [[UIView alloc] initWithFrame:CGRectMake(50, 50, 100, 100)];
testView.backgroundColor = [UIColor redColor];
[self.window addSubview:testView];
UIView* childView = [[UIView alloc] initWithFrame:CGRectMake(30, 30, 80, 80)];
childView.backgroundColor = [UIColor greenColor];
[testView addSubview:childView];
[self.window makeKeyAndVisible];
return YES;
}
分别输出testView和childView的frame、bounds、center属性如下:
testView:
Frame: (50, 50, 100, 100)
Bounds: (0, 0, 100, 100)
Center: (100, 100)
childView:
Frame: (30, 30, 80, 80)
Bounds: (0, 0, 80, 80)
Center: (70, 70)
然后,把testView的bounds属性修改为(50,50,100,100),即:testView本身视图相对于父视图的位置和尺寸不变,不过其自身所在坐标系的原点向左向上分别移动50,这是就与父视图坐标系的原点(屏幕左上角)重合,因此,childView的位置随之改变。这说明修改视图的坐标系原点不影响其位置,但会改变其子视图的位置。
testView.bounds = CGRectMake(50, 50, 100, 100);
分别输出testView和childView的frame、bounds、center属性如下:
testView:
Frame: (50, 50, 100, 100)
Bounds: (50, 50, 100, 100)
Center: (100, 100)
childView:
Frame: (30, 30, 80, 80)
Bounds: (0, 0, 80, 80)
Center: (70, 70)