使用NSLayoutAttribute定义约束。优点是直观,全面(相对/绝对约束都能创建)。但是,其缺点也很致命:啰嗦。每创建一个约束都要不厌其烦的填入7个参数,产生大量重复代码。其结果是代码通货膨胀:写了几百行,界面才刚刚搭好。
NSLayoutAnchor(布局锚点)
面对这种情况,市面上出现了许多第三方库,重新封装原生API,简化约束的创建过程。其中不乏Masonry这样优秀的开源库。
以下是我的代码实例:
@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

注意:
_textField.translatesAutoresizingMaskIntoConstraints = NO;
网友评论