天天看點

UIView中frame, bounds, center三個屬性的關系

在UIView中,有三個重要的屬性:frame, bounds 和 center。這三個屬性之間的關系讓初學者很難了解。下面我通過個人的了解,說說它們的關系。

先記住下面兩句話:

frame的位置是相對父視圖來說的,bounds 和 center 是相對自身來說的。bounds 改變 center 不變,center 改變,bounds 也不變。

每一個UIView都有自身的坐标系。預設坐标系起點都是在左上角。往UIView 添加 view 時是根據其坐标系來計算位置的 。

現在看看基本代碼:

UIView *greenView = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 100, 200)];
    greenView.backgroundColor = [UIColor greenColor];
    [self.window addSubview:greenView];
    [greenView release];
    
    UIView *blueView = [[UIView alloc] initWithFrame:CGRectMake(50, 50, 50, 50)];
    blueView.backgroundColor = [UIColor blueColor];
    [greenView addSubview:blueView];
    [blueView release];
           

運作結果:

UIView中frame, bounds, center三個屬性的關系

以上代碼很簡單,隻是簡單的添加了兩個UIView控件,就不多說了。

現在,我們修改一下greenView的 bounds, 如下代碼:

CGRect newBounds = greenView.bounds;
    newBounds.origin = CGPointMake(50, 0);
    greenView.bounds = newBounds;
           
UIView中frame, bounds, center三個屬性的關系

現在,我們來分析一下:

從結果可以看到,blueView相對于greenView像左移動了50。為什麼會這樣?上面已經說了,每個UIView都有自己的坐标系,而且預設是UIView的左上角。而上面代碼将 greenView的 bounds 屬性修改為 (50, 0, 100, 200)。這時也就是說 greenView 上的 bounds 相對于自身的坐标系的偏移值是:(50,0),如下圖:

UIView中frame, bounds, center三個屬性的關系

(預設情況下)

UIView中frame, bounds, center三個屬性的關系

(修改bounds屬性坐标後)

從圖中可以看出, greenView 在螢幕上的位置不變,隻是其自身的坐标系改變了。是以,在向其添加 blueView時,計算坐标位置就不在是從 greenView的左上角開始計算了。上面,我們隻是把 bounds 的 X 坐标修改了。同理,如果把 greenView 的bounds的坐标改為(-10, -30)那其坐标系就會成下圖中那樣:

UIView中frame, bounds, center三個屬性的關系

現在我們改變一下 greenViewd 下 bounds屬性的 寬和高, 如下代碼:

GRect newBounds = greenView.bounds;
    newBounds.size = CGSizeMake(200, 200);
    greenView.bounds = newBounds;
           

運作結果:

UIView中frame, bounds, center三個屬性的關系

可以發現,greenView 不僅大小變化了,而且位置也改變了。出現這個結果的原因很簡單:還是上面說的那句話:bounds 改變 center 不變。而我們修改了 greenView 的寬度後,它不能隻是想左邊拓展或向右邊拓展(因為這樣的話 center 就改變了),是以為了保持 center 不變隻能向兩邊一起拓展了。于是就有了上面的結果。注:這是自身坐标系沒有變,frame 屬性變了。

如果修改 center 的位置,那 greenView 也會移動,因為 center 是相對自身來說的。

總的來說,要了解這三者的關系,隻要記住上面兩句話:

1. frame的位置是相對父視圖來說的,bounds 和 center 是相對自身來說的。bounds 改變 center 不變,center 改變,bounds 也不變。

2.每一個UIView都有自身的坐标系。預設坐标系起點都是在左上角。往UIView 添加 view 時是根據其坐标系來計算位置的 。