iOS UIView frame,bounds

先看下UIView.h中的解釋

// animatable. do not use frame if view is transformed since it will not correctly reflect the actual location of the view. use bounds + center instead.
@property(nonatomic) CGRect            frame;

// use bounds/center and not frame if non-identity transform. if bounds dimension is odd, center may be have fractional part
@property(nonatomic) CGRect            bounds;      // default bounds is zero origin, frame size. animatable

其中 frame與center是以父視圖作為參照坐標系,而bounds是以自身作為參照坐標系,也就是說,定義bounds的時候,是去給它遠點進行定義

舉個栗子

UIView* v1 = [UIView new];
    v1.backgroundColor = [UIColor redColor];
    v1.frame = CGRectMake(50, 50, 200, 200);
    v1.bounds = CGRectMake(100, 100, 200, 200);
    [self.view addSubview:v1];
    
    UIView* v2 = [UIView new];
    v2.backgroundColor = [UIColor grayColor];
    v2.frame = CGRectMake(60, 60, 200, 200);
    [v1 addSubview:v2];

先看運行結果

屏幕快照 2017-02-22 11.13.01.png

可以看到我們把灰色的view add到紅色的view上
frame為CGRectMake(60, 60, 200, 200)

明顯灰色的view位置已經(jīng)超出紅色的view了。

分析下

 v1.frame = CGRectMake(50, 50, 200, 200);

這段代碼設置了紅色view相對于self.view的位置,所以紅色的view參照坐標系是self.view。

v1.bounds = CGRectMake(100, 100, 200, 200);

此時設置了v1的bounds,可以看到x = 100,y = 100
bounds設置的是自身的坐標系,也就是說,v1的左上角原點在自身坐標系中的坐標為(100,100)

然后在后面代碼中

v2.frame = CGRectMake(60, 60, 200, 200);

v2添加再v1上,它的frame也就是相對于父視圖(v1)的坐標為(60,60)

所以v2的原點在v1的原點左上方。

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容