> IOS开发在线手册 > iOS开发-View中frame和bounds区别

开发中调整View的时候的经常会遇到frame和bounds,刚开始看的时候不是很清楚,不过看了一下官方文档,frame是确定视图在父视图中的位置,和本身的大小,bounds确定可以确定子视图在当前视图中的位置,还可以改变View的大小,如果bounds确定大小,那么View的视图优先选择的bounds中的宽高。Center的位置是相对于父坐标系中的定位。苹果官方给了一张图片供参考:

iOS开发-View中frame和bounds区别

如果还不是很清晰,可以参考一下frame和bounds的中代码:

-(CGRect)frame{
    return CGRectMake(self.frame.origin.x,self.frame.origin.y,self.frame.size.width,self.frame.size.height);
}
-(CGRect)bounds{
    return CGRectMake(0,0,self.frame.size.width,self.frame.size.height);
}

当然为了更好的理解以上的概念,写个小Demo实战了一下,viewDidLoad将图片添加在View中,然后在图片上添加一个View:

UIImageView  *girlImageView=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"Girl.jpg"]];
    girlImageView.frame=CGRectMake(40, 40, 240, 300);

    [self.view addSubview:girlImageView];//添加到父视图中
    NSLog(@"girlImageView frame:%@------girlImageView bounds:%@",NSStringFromCGRect(girlImageView.frame),NSStringFromCGRect(girlImageView.bounds));
    UIView *childView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
    childView.backgroundColor = [UIColor yellowColor];
    [girlImageView addSubview:childView];
    NSLog(@"childView frame:%@-------childView bounds:%@",NSStringFromCGRect(childView.frame),NSStringFromCGRect(childView.bounds));

 具体效果如下:

iOS开发-View中frame和bounds区别

 

输出结果:

2015-04-03 11:50:00.326 MyContraint[1929:98282] girlImageView frame:{{40, 40}, {240, 300}}------girlImageView bounds:{{0, 0}, {240, 300}}
2015-04-03 11:50:00.327 MyContraint[1929:98282] childView frame:{{0, 0}, {100, 100}}-------childView bounds:{{0, 0}, {100, 100}}

 这个时候如果改变一下UIImageView的bounds,代码如下:

   UIImageView  *girlImageView=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"Girl.jpg"]];
    girlImageView.frame=CGRectMake(40, 40, 240, 300);
    //改变View中内部原点的位置,同样可以改变frame的宽高
    [girlImageView setBounds:CGRectMake(-30, -30, 240, 230)];
    [self.view addSubview:girlImageView];//添加到父视图中
    NSLog(@"girlImageView frame:%@------girlImageView bounds:%@",NSStringFromCGRect(girlImageView.frame),NSStringFromCGRect(girlImageView.bounds));

 图片效果:

iOS开发-View中frame和bounds区别

打印效果如下:

2015-04-03 11:57:06.738 MyContraint[2019:102665] girlImageView frame:{{40, 75}, {240, 230}}------girlImageView bounds:{{-30, -30}, {240, 230}}
2015-04-03 11:57:06.739 MyContraint[2019:102665] childView frame:{{0, 0}, {100, 100}}-------childView bounds:{{0, 0}, {100, 100}}

 通过以上的代码的演示,frame和bounds之间的关系应该很清晰了,如果有疑问,欢迎共同探讨~