Autoresizing简介
Autoresizing
是苹果早期屏幕适配的解决办法,当时iOS设备机型很少、屏幕尺寸单一、APP界面相对简单,屏幕适配并没有现在这么复杂,所有的UI控件只要相对父控件布局就可以了。
Autoresizing用法
代码中使用
// 默认YES,子视图会根据父视图的变化而变化。
// default is YES. if set, subviews are adjusted according to their autoresizingMask if self.bounds changes
@property(nonatomic) BOOL autoresizesSubviews;
// 用于设置适配模式,可通过 | 组合多个,如想让设置生效,需要确认父视图开启了autoresizesSubviews。
// simple resize. default is UIViewAutoresizingNone
@property(nonatomic) UIViewAutoresizing autoresizingMask;
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 //与父视图上边间距固定,下边可变
};
例:
- 父视图
superView
设置 autoresizesSubviews YES。 - 父视图宽先设置为:200。
- 子视图
subView
宽设置为:100。 - 给子视图设置适配规则:宽度按照父视图比例缩放
- 把子视图添加到父视图上。
- 修改父视图的宽为:300。
- 子视图自动调整宽为:100 / 200.0 * 300 = 150
// 父视图设置 autoresizesSubviews YES
UIView *superView = [[UIView alloc] init];
superView.autoresizesSubviews = YES;
superView.backgroundColor = [UIColor redColor];
UIView *subView = [[UIView alloc] init];
subView.backgroundColor = [UIColor greenColor];
// 子视图设置 autoresizingMask 为:距离父视图顶部、左边距、右边距不变,宽度按照父视图比例缩放
subView.autoresizingMask =
UIViewAutoresizingFlexibleWidth |
UIViewAutoresizingFlexibleBottomMargin |
UIViewAutoresizingFlexibleRightMargin |
UIViewAutoresizingFlexibleLeftMargin;
superView.frame = CGRectMake(0, 0, 200, 300);
subView.frame = CGRectMake(0, 0, 100, 120);
// 子视图添加到父视图,且此时父视图frame有值时,会创建依赖关系。
[superView addSubview:subView];
// 在之后修改父视图frame,子视图会按照设定的布局进行自动调整。子视图宽为:100 / 200.0 * 300 = 150
superView.frame = CGRectMake(0, 0, 300, 300);
NSLog(@"superView:%@", NSStringFromCGRect(superView.frame));
NSLog(@"subView:%@", NSStringFromCGRect(subView.frame));
运行后打印结果为:
superView:{{0, 0}, {300, 300}}
subView:{{0, 0}, {150, 120}}
xib中使用
Autoresizing的各种组合预览
-
左、上间距固定
x、y、w、h都不会变
代码表现
UIViewAutoresizingFlexibleRightMargin
|UIViewAutoresizingFlexibleBottomMargin
xib表现
2021-12-29 11.51.52.gif
-
左、右、上间距固定、高度固定
x、y、h不会变,w会变
代码表现
UIViewAutoresizingFlexibleBottomMargin
|UIViewAutoresizingFlexibleWidth
xib表现
2021-12-29 11.52.27.gif
-
左、右、上间距固定
x、y不会变,w、h会变
代码表现
UIViewAutoresizingFlexibleBottomMargin
|UIViewAutoresizingFlexibleWidth
|
UIViewAutoresizingFlexibleHeight
xib表现
2021-12-29 11.53.01.gif
-
左、右、上、下间距固定
x、y不会变,w、h会变
代码表现
UIViewAutoresizingFlexibleWidth
|UIViewAutoresizingFlexibleHeight
xib表现
2021-12-29 11.53.17.gif
说明:宽高跟随父视图变化时,是按照初始比例进行缩放。
其他文章:
iOS-屏幕适配(Autoresizing)
网友评论