frame、bounds与center属性

最近看到同事代码里面有好多感觉bounds,frame,center这三个东西错用,这里写写三者的差别
UIView类中定义了三个属性,分别是frame、bounds与center属性:

    @property(nonatomic) CGRect frame;  
    @property(nonatomic) CGRect bounds;  
    @property(nonatomic) CGPoint center;  

在详细介绍这三个属性之前,我们应该知道UIKit中的坐标系X轴正方向为水平向右,Y轴正方向为竖直向下。

frame属性指的是视图在其父视图坐标系中的位置与尺寸。在创建视图时,我们就需要在初始化方法中指定视图的frame:

派生到我的代码片

    - (id)initWithFrame:(CGRect)frame;  

这样创建了视图之后,通过addSubview:方法就可以将创建的子视图放置在父视图的指定位置,并以指定的尺寸显示出来。

center属性理解起来也很简单,它就是视图的中心点在其父视图坐标系中的位置坐标。简单讲,center属性就定义了当前视图在父视图中的位置。

那么bounds属性呢?它指的是视图在其自己的坐标系中的位置与尺寸。

    - (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];  

        NSLog(@"Frame: (%.2f, %.2f, %.2f, %.2f)", testView.frame.origin.x, testView.frame.origin.y, testView.frame.size.width, testView.frame.size.height);  
        NSLog(@"Bounds: (%.2f, %.2f, %.2f, %.2f)", testView.bounds.origin.x, testView.bounds.origin.y, testView.bounds.size.width, testView.bounds.size.height);  
        NSLog(@"Center: (%.2f, %.2f)", testView.center.x, testView.center.y);  

        [self.window makeKeyAndVisible];  
        return YES;  
    }  
    Frame: (50.00, 50.00, 100.00, 100.00)  
    Bounds: (0.00, 0.00, 100.00, 100.00)  
    Center: (100.00, 100.00)  

由于视图的定位一定需要针对父视图,而不是针对自己,所以bounds属性并不能够决定当前视图的位置(因为它与父视图根本无关,就谈不上定位),所以bounds属性与center属性是完全独立的,前者规定尺寸,后者定义位置。换句话说,修改bounds不影响center;修改center不影响bounds。这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值