前言:
autoresizing是iOS在autoLayout出現(xiàn)之前的界面自動(dòng)化布局方式,但是,由于該方法的局限性,只能用于子控件適應(yīng)父控件的布局改變,所以,蘋果官方后面出了autoLayout,一種能適應(yīng)更復(fù)雜場(chǎng)景的自動(dòng)化布局方式。
1.簡(jiǎn)單的使用
\\子控件相對(duì)于父控件右邊的間距不變
UIView *testView = [[UIView alloc] initWithFrame: CGRectMake(0, 0, 120, 80)];
testView.backgroundColor = [UIColor orangeColor];
UIView *otherView = [[UIView alloc] initWithFrame: CGRectMake(5, 5, 40, 40)];
otherView.backgroundColor = [UIColor blueColor];
otherView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin; //左邊間距可變,那么默認(rèn)其它間距不變,比如頂部間距,底部間距和右邊間距,寬高等等
[testView addSubview: otherView];
[self.view addSubview: testView];
//改變父控件的frame
testView.frame = CGRectMake(0, 0, 200, 120);
效果圖:

autoMaskLeft.gif
上面的動(dòng)圖除了左邊間距改變了,底部間距也改變了,因?yàn)檫@里涉及到兩個(gè)間距,一個(gè)就是底部間距,還有一個(gè)就是控件本身的高度,很明顯高度不變的優(yōu)先級(jí)比底部間距不變的優(yōu)先級(jí)高,所以,底部間距改變了,而高度不變。
2.view的autoresizingMask屬性
typedef NS_OPTIONS(NSUInteger, UIViewAutoresizing) {
UIViewAutoresizingNone = 0, //默認(rèn)選項(xiàng),效果就是頂部和左邊距離父控件不變,并且寬高也不變
UIViewAutoresizingFlexibleLeftMargin = 1 << 0, //與父控件右邊間距不可變,左邊可變
UIViewAutoresizingFlexibleWidth = 1 << 1, //視圖寬度可變
UIViewAutoresizingFlexibleRightMargin = 1 << 2, //與父控件左邊間距不可變,右邊可變
UIViewAutoresizingFlexibleTopMargin = 1 << 3, //與父控件底部間距不可變,頂部可變
UIViewAutoresizingFlexibleHeight = 1 << 4, //視圖高度可變
UIViewAutoresizingFlexibleBottomMargin = 1 << 5 //與父控件頂部間距不可變,底部可變
};
//注:由于是options,所以可以多選,用"|"符隔開就行
3.羅列出基本選項(xiàng)的效果以及一些組合選項(xiàng)的效果
(1)右邊間距可變
otherView.autoresizingMask = UIViewAutoresizingFlexibleRightMargin;

autoMaskRight.gif
(2)頂部間距可變
otherView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;

autoMaskTop.gif
(3)底部間距可變
otherView.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin;

autoMaskBottom.gif
(4)左邊和右邊的間距可變
otherView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;

autoMaskLToR.gif
(5)寬度可變
otherView.autoresizingMask = UIViewAutoresizingFlexibleWidth;

autoMaskWidth.gif
(6)高度可變
otherView.autoresizingMask = UIViewAutoresizingFlexibleHeight;

autoMaskHeight.gif
(7)高度和寬度可變
otherView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

autoMaskWAndH.gif
(8)左邊間距和高度可變
otherView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleHeight;

autoMaskLAndH.gif
(9)左邊間距和寬度可變
otherView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleWidth;

autoMaskLAndW.gif
注:還可以三個(gè)屬性以及更多屬性組合,可以自己嘗試一下各種組合效果如何,這里不做過多說明。
4.總結(jié)
在最后點(diǎn)個(gè)題,使用autoresizing來自動(dòng)化布局局限性還是很明顯的,從蘋果只給出了一個(gè)可選的屬性就可以知道,變化空間不大。所以,如果想要更復(fù)雜的效果,還是選擇autoLayout,無(wú)論原生的還是第三方庫(kù)。