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];
}
}