1. Autoresizing特性
当UIView的autoresizesSubviews是YES时,(默认是YES), 那么在其中的子view会根据它自身的autoresizingMask属性来自动适应其与superView之间的位置和大小。autoresizingMask是一个枚举类型, 默认是UIViewAutoresizingNone, 也就是不会autoresize:
typedef NS_OPTIONS(NSUInteger, UIViewAutoresizing) {
UIViewAutoresizingNone = 0,
UIViewAutoresizingFlexibleLeftMargin = 1 << 0, // 将1的二进制左移0位
UIViewAutoresizingFlexibleWidth = 1 << 1,
UIViewAutoresizingFlexibleRightMargin = 1 << 2,
UIViewAutoresizingFlexibleTopMargin = 1 << 3,
UIViewAutoresizingFlexibleHeight = 1 << 4,
UIViewAutoresizingFlexibleBottomMargin = 1 << 5
};
其实如何理解这几个值很简单,那就是从xib里面看。 我们在一个xib文件中,取消勾选autolayout,(默认使用autolayout时,autoresizing看不到)。那么我们可以在布局那一栏看到如何设置autoresizing.
上图说明了在xib中设置的这些线条和实际属性对应的关系,这其中需要注意的是,其中4个margin虚线才代表设置了该值,而width和height是实线代表设置了该值,不能想当然的理解。
这些项分别代表:
autoresizingMask是子视图的左、右、上、下边距以及宽度和高度相对于父视图按比例变化,例如:
UIViewAutoresizingNone 不自动调整。
UIViewAutoresizingFlexibleLeftMargin 自动按比例调整与superView左边的距离,且与superView右边的距离不变。
UIViewAutoresizingFlexibleRightMargin 自动按比例调整与superView的右边距离,且与superView左边的距离不变。
UIViewAutoresizingFlexibleTopMargin 自动按比例调整与superView的顶部距离,且与superView底部的距离不变。
UIViewAutoresizingFlexibleBottomMargin 自动按比例调整与superView的底部距离,且与superView顶部的距离不变。
UIViewAutoresizingFlexibleWidth 自动按比例调整宽度。
UIViewAutoresizingFlexibleHeight 自动按比例调整高度。
UILabel* label = [[UILabel alloc] initWithFrame:CGRectMake(50, 100, 200, 40)];
[label setAutoresizingMask: UIViewAutoresizingNone]; 控件相对于父视图坐标值不变
CGRectMake(50, 100, 200, 40)
UIViewAutoresizingFlexibleWidth:控件的宽度随着父视图的宽度按比例改变 例如
label宽度为 100 屏幕的宽度为320 当屏幕宽度为480时 label宽度 变为 100*480/320
2. 小结
Autoreszing的最常见的实用场景就是iPhone5的兼容了。
- 比如我们想要设置tableView的frame,那我们只需要在初始化设置frame之后将tableView的autoresizingMask设置为UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight 就行了。
- 另一种比如我们想要一个view一直停留在其superview的最下方,那么我们在初始化设置frame之后只需要将autoresizingMask设置为UIViewAutoresizingFlexibleTopMargin 就可以了。
autorezingMask是很简单的一个属性,理解它之后可以让很多事情变得简单。