一,概述
autoresizing是iOS开发中传统的布局模式。通过它可以设计控件与其父视图的变换关系,从而实现iOS中传统的界面自动布局的效果。也就是说当父视图frame变换时,子视图在设置autoresizingMask属性相关的条件下会自动的做出相应的调整。
iOS有两大自动布局利器:autoresizing 和 autolayout(autolayout是IOS6以后新增)。autoresizing是UIView的属性,一直存在,使用也比较简单,但是没有autolayout那样强大。autoresizing只能设置子视图相对于父视图的变化,却不能精确到具体变化了多少,因此对于复杂的精准的布局需求,autoLayout是你不错的选择。如果在你的界面比较简单,要求的细节没有那么高的情况下,你也完全可以使用autoresizing去进行自动布局。
伴随着autoresizingMask 属性,还要autoresizesSubviews属性。假如父视图将自身的autoresizesSubviews 设置成NO,那么该父视图相应的直接子视图的所有的自动尺寸调整行为将被忽略。同样的一个子视图的自动尺寸调整掩码(autoresizingMask属性)被设置为 UIViewAutoresizingNone,则该子视图的尺寸将不会被调整。
二,关于autoresizingMask的枚举
UIViewAutoresizing是一个枚举类型,默认是UIViewAutoresizingNone,即不做任何处理。
typedef NS_OPTIONS(NSUInteger, UIViewAutoresizing) {
UIViewAutoresizingNone = 0, //不会随父视图的改变而改变。
UIViewAutoresizingFlexibleLeftMargin = 1 << 0, //自动调整view与父视图左边距,以保证右边距不变
UIViewAutoresizingFlexibleWidth = 1 << 1, //自动调整view的宽度,保证左边距和右边距不变
UIViewAutoresizingFlexibleRightMargin = 1 << 2, //自动调整view与父视图右边距,以保证左边距不变
UIViewAutoresizingFlexibleTopMargin = 1 << 3, //自动调整view与父视图上边距,以保证下边距不变
UIViewAutoresizingFlexibleHeight = 1 << 4, //自动调整view的高度,以保证上边距和下边距不变
UIViewAutoresizingFlexibleBottomMargin = 1 << 5 //自动调整view与父视图的下边距,以保证上边距不变
};
autoresizing组合使用:
也就是枚举中的值可以使用|隔开,同时拥有多个值的功能,可以针对不同的场景作不同的变化。例如:
UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleBottomMargin
意思是:view的宽度按照父视图的宽度比例进行缩放,距离父视图顶部距离不变。
三,运用autoresizing布局的两种情景
1.通过代码布局
#import "ViewController.h"
#define topSpace 64
#define kMargin 20
#define kTopViewHeight 200
#define kTopViewWidth 300
#define kTextLabelWidth 200
#define kTextLabelHeight 100
#define ChangeSpace 40
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self autoresizingMaskdemo];
}
-(void)autoresizingMaskdemo{
UIView * bottomView = [[UIView alloc]initWithFrame:CGRectMake(kMargin,topSpace, kTopViewWidth, kTopViewHeight)];;
bottomView.backgroundColor = [UIColor redColor];
UILabel * topLabel = [[UILabel alloc]initWithFrame:CGRectMake(kMargin,kMargin/2, kTextLabelWidth, kTextLabelHeight)];
topLabel.text =@"父视图frame未改变";
topLabel.backgroundColor =[UIColor blueColor];
topLabel.textColor = [UIColor yellowColor];
topLabel.autoresizingMask =UIViewAutoresizingNone;
[self.view addSubview:bottomView];
[bottomView addSubview:topLabel];
//动态改变frame,测试效果
[UIView animateWithDuration:1 animations:^{
bottomView.frame =CGRectMake(kMargin, topSpace, kTopViewWidth+ChangeSpace, kTopViewHeight+ChangeSpace);
} completion:^(BOOL finished) {
topLabel.text =@"父视图frame改变了";
}];
}
2.通过xib布局