約束布局 - NSLayoutAnchor

http://m.itdecent.cn/p/b94b28a8a642

使用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;

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容