開始以前先推薦老外封裝好的開源庫Masonry,Masonry是一個輕量級的佈局框架,擁有本身的描述語法,簡潔明瞭並具備高可讀性。下面得例子用系統API實現一個和Masonry同樣得佈局,點擊一個Button改變尺寸,Button尺寸不能超過VC界面; git
添加一個button在VC中心 github
@interface PPBUpdateVC() @property (nonatomic,strong) UIButton *growingButton; @property (nonatomic,strong) NSLayoutConstraint *layoutWith; @property (nonatomic,strong) NSLayoutConstraint *layoutHeight; @end
添加button 框架
self.growingButton = [UIButton buttonWithType:UIButtonTypeSystem]; [self.growingButton setTitle:@"Grow Me!" forState:UIControlStateNormal]; self.growingButton.layer.borderColor = UIColor.greenColor.CGColor; self.growingButton.layer.borderWidth = 3; self.growingButton.translatesAutoresizingMaskIntoConstraints = NO; [self.growingButton addTarget:self action:@selector(didTapGrowButton:) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:self.growingButton];
添加寬度約束 ide
self.layoutWith = [NSLayoutConstraint
constraintWithItem:self.growingButton
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:nil
attribute:NSLayoutAttributeNotAnAttribute
multiplier:1.0
constant:100];
self.layoutWith.priority = UILayoutPriorityDefaultHigh;
[self.growingButton addConstraint:self.layoutWith];
添加高度約束 佈局
self.layoutHeight = [NSLayoutConstraint constraintWithItem:self.growingButton attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:100]; self.layoutHeight.priority = UILayoutPriorityDefaultHigh; [self.growingButton addConstraint:self.layoutHeight];
添加中心點約束 atom
NSLayoutConstraint *centerX = [NSLayoutConstraint constraintWithItem:self.growingButton attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0]; NSLayoutConstraint *centerY = [NSLayoutConstraint constraintWithItem:self.growingButton attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0]; [self.view addConstraint:centerX]; [self.view addConstraint:centerY];
添加button的最大寬度和高度,這裏要注意的是,對同一個屬性添加多個約束要設置優先級,不然會報錯。 spa
self.layoutWith.priority = UILayoutPriorityDefaultHigh;
NSLayoutConstraint *maxWidth = [NSLayoutConstraint constraintWithItem:self.growingButton attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationLessThanOrEqual toItem:self.view attribute:NSLayoutAttributeWidth multiplier:1.0 constant:0]; [self.view addConstraint:maxWidth]; [self.view addConstraint: [NSLayoutConstraint constraintWithItem:self.growingButton attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationLessThanOrEqual toItem:self.view attribute:NSLayoutAttributeHeight multiplier:1.0 constant:0]]; }
button點擊事件 code
- (void)didTapGrowButton:(UIButton *)button { self.layoutHeight.constant = self.layoutHeight.constant * 1.3; self.layoutWith.constant = self.layoutWith.constant * 1.3; [UIView animateWithDuration:0.4 animations:^{ [self.growingButton layoutIfNeeded]; }]; }