使用NSLayoutAttribute定義約束。優(yōu)點(diǎn)是直觀,全面(相對(duì)/絕對(duì)約束都能創(chuàng)建)。但是,其缺點(diǎn)也很致命:啰嗦。每創(chuàng)建一個(gè)約束都要不厭其煩的填入7個(gè)參數(shù),產(chǎn)生大量重復(fù)代碼。其結(jié)果是代碼通貨膨脹:寫了幾百行,界面才剛剛搭好。
NSLayoutAnchor(布局錨點(diǎn))
面對(duì)這種情況,市面上出現(xiàn)了許多第三方庫,重新封裝原生API,簡化約束的創(chuàng)建過程。其中不乏Masonry這樣優(yōu)秀的開源庫。
以下是我的代碼實(shí)例:
@interface ViewController ()
@property (nonatomic, strong)NSMutableArray *buttons;
@property (weak) IBOutlet NSView *containView;
@property (strong) NSTextField *textField;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.containView.wantsLayer = true;
[self.containView.layer setBackgroundColor:NSColor.yellowColor.CGColor];
[self.containView setAutoresizesSubviews:false];
_buttons = [NSMutableArray arrayWithCapacity:0];
_textField = [[NSTextField alloc]init];
_textField.translatesAutoresizingMaskIntoConstraints = NO;
[self.containView addSubview:_textField];
// NSLayoutConstraint *labelH = [NSLayoutConstraint constraintWithItem:_textField attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeHeight multiplier:1.0 constant:20];
// [_textField updateConstraint:labelH withIdentifier:@"textField_H"];
//
// NSLayoutConstraint *labelW = [NSLayoutConstraint constraintWithItem:_textField attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeWidth multiplier:1.0 constant:120];
// labelW.active = true;
// [_textField updateConstraint:labelW withIdentifier:@"textField_W"];
//上面注釋部分效果等于下面四行
NSLayoutConstraint *labelH = [_textField.heightAnchor constraintEqualToConstant:20];
[_textField updateConstraint:labelH withIdentifier:@"textField_H"]; //分類方法 用來添加約束
NSLayoutConstraint *labelW = [_textField.widthAnchor constraintEqualToConstant:120];
[_textField updateConstraint:labelW withIdentifier:@"textField_W"]; //分類方法 用來添加約束
NSLayoutConstraint *labelLeading = [_textField.leadingAnchor constraintEqualToAnchor:self.containView.leadingAnchor constant:30];
labelLeading.active = true;
[self.containView updateConstraint:labelLeading withIdentifier:@"labelLeading"]; //分類方法 用來添加約束
NSLayoutConstraint *labelCenterY = [_textField.centerYAnchor constraintEqualToAnchor:self.containView.centerYAnchor];
labelCenterY.active = true;
[self.containView updateConstraint:labelCenterY withIdentifier:@"labelCenterY"]; //分類方法 用來添加約束
// Do any additional setup after loading the view.
}
@end

image.png
注意:
_textField.translatesAutoresizingMaskIntoConstraints = NO;