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
autoLayout是子视图相对于某个视图(可以是父视图也可以是同级兄弟视图)的位置,在屏幕尺寸发生变化时,相对位置保持不变。例如:
- (void)viewDidLoad
{
[superviewDidLoad];
self.btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
self.btn.backgroundColor = [UIColorredColor];
[self.btn setTitle:@"MyBtn"forState:UIControlStateNormal];
[self.view addSubview:self.btn];
//禁止自动转换AutoresizingMask
self.btn.translatesAutoresizingMaskIntoConstraints = NO;
//在页面水平居中显示按钮。
[self.view addConstraint: [NSLayoutConstraint constraintWithItem:self.btn
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeCenterX
multiplier:1.0
constant:0]];
//距离顶部100像素显示按钮。
[self.viewaddConstraint:[NSLayoutConstraint constraintWithItem:self.btn
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeTop
multiplier:1.0
constant:100.0]];
//定义高度是父View的三分之一。
[self.viewaddConstraint:[NSLayoutConstraintconstraintWithItem:self.btn
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeHeight
multiplier:(1.0/3.0)
constant:0]];
//定义宽度是父View的三分之一。
[self.viewaddConstraint:[NSLayoutConstraint constraintWithItem:self.btn
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeWidth
multiplier:(1.0/3.0)
constant:0]];
//注册KVO(Key-Value Observing)方法。
[self.btnaddObserver:selfforKeyPath:@"bounds"options:NSKeyValueObservingOptionInitial |NSKeyValueObservingOptionNew context:nil];
}
//KVO回调。
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if (object ==self.btn && [keyPathisEqualToString:@"bounds"]) {
self.btn.backgroundColor = [UIColorgreenColor];
[self.btnsetTitle:NSStringFromCGSize(self.btn.bounds.size)forState:UIControlStateNormal];
}
}