iOS autoresizing佈局

在對UIView以及其子類空間的佈局方案有多種,今天溫習了一下autoresizing佈局編程

 

1、瞭解一下相關知識:佈局

一、UIView其中一個屬性爲atom

  @property(nonatomic) UIViewAutoresizing autoresizingMask;    // simple resize. default is UIViewAutoresizingNonespa

  該佈局方案主要是對該屬性的設置orm

二、UIViewAutoresizing爲可選類型( NS_OPTIONS、NS_ENUM略有不一樣)blog

typedef NS_OPTIONS(NSUInteger, UIViewAutoresizing) {it

    UIViewAutoresizingNone                 = 0,   //不會隨父視圖的改變而改變class

    UIViewAutoresizingFlexibleLeftMargin   = 1 << 0,   //自動調整view與父視圖左邊距,以保證右邊距不變方法

    UIViewAutoresizingFlexibleWidth        = 1 << 1,   //自動調整view的寬度,保證左邊距和右邊距不變im

    UIViewAutoresizingFlexibleRightMargin  = 1 << 2,  //自動調整view與父視圖右邊距,以保證左邊距不變

    UIViewAutoresizingFlexibleTopMargin    = 1 << 3,  //自動調整view與父視圖上邊距,以保證下邊距不變

    UIViewAutoresizingFlexibleHeight       = 1 << 4,  //自動調整view的高度,以保證上邊距和下邊距不變

    UIViewAutoresizingFlexibleBottomMargin = 1 << 5  //自動調整view與父視圖的下邊距,以保證上邊距不變

};

 

2、想要在xib或者storyboard上使用此佈局方案,要講默認的佈局方案(AutoLayout以及Size classes)關閉

 

在純代碼編程中使用此佈局時須要注意:

  UIView的autoresizesSubviews屬性爲yes時(默認爲yes),autoresizing纔會生效。

 

 3、以xib爲例

好久沒有使用xib,剛使用過程當中還出現一點之前遇到的問題:

loaded the "TestViewController" nib but the view outlet was not set.

解決方法:右擊File's Owner ,在彈出列表中的view項右擊連線到xib便可(即將此view設置爲File's Owner的屬性),以下圖

休息片刻以後,繼續回來:

下圖中給橙色控件的autoresizingMask屬性設置的值有四個UIViewAutoresizingFlexibleRightMargin、UIViewAutoresizingFlexibleWidth、UIViewAutoresizingFlexibleLeftMargin、UIViewAutoresizingFlexibleBottomMargin(順序從左到右、從上到下),目的是讓橙色button的左邊距、右邊距、上邊距固定,寬度可變、高度不變,在任何尺寸的屏幕下都是如此!

 

 此效果用代碼顯示的話爲

 self.view.autoresizesSubviews = YES;

    CGFloat margin = 8;

    CGFloat buttonY = 65;

    CGFloat height = 143;

    CGFloat width = [UIScreen mainScreen].bounds.size.width - margin * 2;

    UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(margin, buttonY, width, height)];

    [btn setTitle:@"Autoresizing" forState:UIControlStateNormal];

    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];

    [btn setBackgroundColor:[UIColor orangeColor]];

    [self.view addSubview:btn];

     // autoresizing佈局

    btn.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleBottomMargin;

便可展現和xib同樣的效果

 

在此過程當中,出現個小小的問題,就是橫屏、豎屏切換過程當中,導航欄高度變化,會致使上邊距有變化(效果上看來是上邊距變化),

想了一下解決辦法,代碼以下

self.edgesForExtendedLayout = UIRectEdgeNone; // 佈局時忽略導航欄高度(iOS7以後的屬性)

這樣就能夠避免導航欄高度隨橫豎屏切換變化對佈局產生的影響! 

相關文章
相關標籤/搜索