在iOS應用的開發過程當中,常常會使用,setFrame的方式對UIView進行佈局,app
常常會使用計算的方式,如self.view.bounds.size.height - 20-44- Heignt等來計算Y的相對位置ide
咱們知道上邊的數字 20是status bar的高度,44是navigationBar的高度.佈局
這樣的寫法沒有什麼錯誤,可是不利於代碼的複用,好比一個ViewController在建立的時候,有可能有navigationController,也可能沒有navigationController,在這種狀況下,這個VIewController裏邊的子UIView的相對位置就可能出現誤差.url
因此,本文主要介紹autoresizingMask屬性,對UIVIew進行相對的佈局。spa
假設以下的需求:.net
程序啓動後,構建一個自定義的TabBar,始終顯示在應用的底部,不管屏幕發生旋轉,或者收到來電的狀況下,都顯示在應用的底部。(看起來,跟如今的不少微博客戶端類似,它們多半都沒有使用系統的tabbarcontroller方式,而是本身繪製的tabbar).orm
能夠用以下的代碼來實現blog
- (void)viewDidLoad ip
{ 開發
[super viewDidLoad];
self.tabbar = [[[CustumTabBar alloc] init] autorelease];
[self.tabbar setFrame:CGRectMake(0, self.view.bounds.size.height -44, self.view.bounds.size.width, 44)];
self.tabbar.autoresizingMask = UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleWidth;
[self.tabbar setBackgroundColor:[UIColor blueColor]];
[self.view addSubview:self.tabbar];
}
同理,若是想讓一個UIVIew始終都在屏幕中心,
能夠設置它的Y爲 ceilf((self.view.bounds.size.height - Height)/2),
同時設置autoresizingMask = UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleBottomMargin 便可。