欢迎加入【iOS/Swift/OC开发交流群|127183325】交流学习
iOS有两个自动布局方式:
- autoresizing
- autolayout,这个布局方式是iOS6以后新增的
autoresizingMask是UIView的属性,使用起来比较简单。如果你的应用的界面比较简单,就可以使用autoresizing进行自动布局。
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 | 自动调整与父视图左边距,保持右边距不变 |
UIViewAutoresizingFlexibleWidth | 自动调整本身的宽度,保持和父视图的左右边距不变 |
UIViewAutoresizingFlexibleRightMargin | 自动调整与父视图右边距,保持左边距不变 |
UIViewAutoresizingFlexibleTopMargin | 自动调整与父视图上边距,保持下边距不变 |
UIViewAutoresizingFlexibleHeight | 自动调整本身的高度,保持上边距和下边距不变 |
UIViewAutoresizingFlexibleBottomMargin | 自动调整与父视图的下边距,保持上边距不变 |
这些属性是可以组合使用的,比如:
UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleBottomMargin
view的宽度随着父视图的变化进行自动调整,自动调整与父视图的下边距,与父视图的上边距保持不变。
注意:
UIView的 autoresizesSubviews属性为YES时,上述属性才能生效,默认为YES。
附一段代码可以运行看看效果:
//
// ViewController.m
// HPSwitchViewDemo
//
// Created by 韩学鹏 on 16/10/10.
// Copyright © 2016年 韩学鹏. 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
就当前的代码来说,当点击的时候父视图的宽度会减小,子视图会为了保持与父视图的左右边距不变,宽度会随着父视图的变小而变小。