autoResizingMask 是UIView的一個屬性,在一些簡單的布局中,使用autoResizingMask,可以實現子控件相對於父控件的自動布局。
autoResizingMask 是UIViewAutoresizing 類型的,其定義為:
@property(nonatomic) UIViewAutoresizing autoresizingMask; // simple resize. default is UIViewAutoresizingNone
UIViewAutoresizing 是一個枚舉類型,默認是 UIViewAutoresizingNone,其可以取得值有:
typedef NS_OPTIONS(NSUInteger, UIViewAutoresizing) { UIViewAutoresizingNone = 0, UIViewAutoresizingFlexibleLeftMargin = 1 << 0, UIViewAutoresizingFlexibleWidth = 1 << 1, UIViewAutoresizingFlexibleRightMargin = 1 << 2, UIViewAutoresizingFlexibleTopMargin = 1 << 3, UIViewAutoresizingFlexibleHeight = 1 << 4, UIViewAutoresizingFlexibleBottomMargin = 1 << 5 };
各屬性解釋:
UIViewAutoresizingNone |
不會隨父視圖的改變而改變 |
UIViewAutoresizingFlexibleLeftMargin |
自動調整view與父視圖左邊距,以保證右邊距不變 |
UIViewAutoresizingFlexibleWidth |
自動調整view的寬度,保證左邊距和右邊距不變 |
UIViewAutoresizingFlexibleRightMargin |
自動調整view與父視圖右邊距,以保證左邊距不變 |
UIViewAutoresizingFlexibleTopMargin |
自動調整view與父視圖上邊距,以保證下邊距不變 |
UIViewAutoresizingFlexibleHeight |
自動調整view的高度,以保證上邊距和下邊距不變 |
UIViewAutoresizingFlexibleBottomMargin |
自動調整view與父視圖的下邊距,以保證上邊距不變 |
注意:autoResizingMask 既可以在代碼中直接使用,也可以在UIStoryboard中使用。
一個代碼中使用autoResizingMask的例子:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; UIViewController *viewController = [[UIViewController alloc] init]; self.window.rootViewController = viewController; self.window.backgroundColor = [UIColor whiteColor]; UIView *view = [[UIView alloc] initWithFrame:CGRectMake(20,100,200,100)]; [view setBackgroundColor:[UIColor grayColor]]; [self.window addSubview:view]; UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(20,20,50,50)]; [button setBackgroundColor:[UIColor whiteColor]]; [view addSubview:button]; //距離父視圖右邊距不變 //button.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin; //距離父視圖的左邊距不變 //button.autoresizingMask = UIViewAutoresizingFlexibleRightMargin; //距離父視圖的左右邊距不變,button大小會調整 //button.autoresizingMask = UIViewAutoresizingFlexibleWidth; //view.frame = CGRectMake(20,100,300,100); //距離父視圖的下邊距不變 //button.autoresizingMask = UIViewAutoresizingFlexibleTopMargin; //距離父視圖的上邊距不變 //button.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin; //距離父視圖的上下邊距不變,button大小會調整 button.autoresizingMask = UIViewAutoresizingFlexibleHeight; view.frame = CGRectMake(20,100,200,200); [self.window makeKeyAndVisible]; return YES; }
另外,autoResizingMask 可以組合使用。例如:
button.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleLeftMargin;
表示的是,子控件相對於父控件的頂部和右側的距離不變。