歡迎加入【iOS/Swift/OC開發(fā)交流群|127183325】交流學(xué)習(xí)
iOS有兩個自動布局方式:
- autoresizing
- autolayout桃移,這個布局方式是iOS6以后新增的
autoresizingMask是UIView的屬性喊递,使用起來比較簡單。如果你的應(yīng)用的界面比較簡單,就可以使用autoresizing進行自動布局筛严。
UIViewAutoresizing是一個枚舉類型,默認(rèn)類型是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 | 自動調(diào)整與父視圖左邊距辣卒,保持右邊距不變 |
UIViewAutoresizingFlexibleWidth | 自動調(diào)整本身的寬度掷贾,保持和父視圖的左右邊距不變 |
UIViewAutoresizingFlexibleRightMargin | 自動調(diào)整與父視圖右邊距,保持左邊距不變 |
UIViewAutoresizingFlexibleTopMargin | 自動調(diào)整與父視圖上邊距荣茫,保持下邊距不變 |
UIViewAutoresizingFlexibleHeight | 自動調(diào)整本身的高度想帅,保持上邊距和下邊距不變 |
UIViewAutoresizingFlexibleBottomMargin | 自動調(diào)整與父視圖的下邊距,保持上邊距不變 |
這些屬性是可以組合使用的啡莉,比如:
UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleBottomMargin
view的寬度隨著父視圖的變化進行自動調(diào)整港准,自動調(diào)整與父視圖的下邊距旨剥,與父視圖的上邊距保持不變。
注意:
UIView的 autoresizesSubviews屬性為YES時浅缸,上述屬性才能生效轨帜,默認(rèn)為YES。
附一段代碼可以運行看看效果:
//
// ViewController.m
// HPSwitchViewDemo
//
// Created by 韓學(xué)鵬 on 16/10/10.
// Copyright ? 2016年 韓學(xué)鵬. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()
@property (nonatomic, weak) UIView *myView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//這個view作為一個父視圖
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(20, 50, 300, 300)];
view.backgroundColor = [UIColor blueColor];
[self.view addSubview:view];
view.autoresizesSubviews = YES;
self.myView = view;
//子視圖
UIView *view0 = [[UIView alloc] initWithFrame:CGRectMake(10, 10, 150, 150)];
view0.backgroundColor = [UIColor greenColor];
view0.autoresizingMask = UIViewAutoresizingFlexibleWidth;
[view addSubview:view0];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
CGRect frame = self.myView.frame;
frame = CGRectMake(frame.origin.x, frame.origin.y, frame.size.width-10, frame.size.height);
self.myView.frame = frame;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
就當(dāng)前的代碼來說衩椒,當(dāng)點擊的時候父視圖的寬度會減小蚌父,子視圖會為了保持與父視圖的左右邊距不變,寬度會隨著父視圖的變小而變小毛萌。