iOS Autolayout 约束设置【顺序】的重要性!

0x00 顺序不同,结果不同

看图说话 1

iOS Autolayout 约束设置【顺序】的重要性!_第1张图片

代码是这样滴~
设置好约束,让 4 个按钮,宽度均分~
结果如上图

    [_pastButton.topAnchor constraintEqualToAnchor:_textView.bottomAnchor constant:6].active = YES;
    [_pastButton.leftAnchor constraintEqualToAnchor:_textView.leftAnchor].active = YES;
    [_pastButton.heightAnchor constraintEqualToConstant:44].active = YES;
    
    NSArray *buttons = @[_pastButton, _deleteButton, _breakButton, _inputButton];
    for (NSInteger i = 0; i < buttons.count-1; i++) {
        UIButton *button1 = buttons[i];
        UIButton *button2 = buttons[i+1];
        
        [button2.topAnchor constraintEqualToAnchor:button1.topAnchor].active = YES;
        [button2.leftAnchor constraintEqualToAnchor:button1.rightAnchor constant:10].active = YES;
        [button2.heightAnchor constraintEqualToAnchor:button1.heightAnchor].active = YES;
        [button2.widthAnchor constraintEqualToAnchor:button1.widthAnchor].active = YES;
        
        if (i == buttons.count-1) {
            [button2.rightAnchor constraintEqualToAnchor:_textView.rightAnchor].active = YES;
        }
    }

看图说话 2

iOS Autolayout 约束设置【顺序】的重要性!_第2张图片

代码是这样滴~
设置好约束,让 4 个按钮,宽度均分~
结果如上图,完美!

    [_pastButton.topAnchor constraintEqualToAnchor:_textView.bottomAnchor constant:6].active = YES;
    [_pastButton.leftAnchor constraintEqualToAnchor:_textView.leftAnchor].active = YES;
    [_pastButton.heightAnchor constraintEqualToConstant:44].active = YES;
    
    [_inputButton.rightAnchor constraintEqualToAnchor:_textView.rightAnchor].active = YES;
    
    NSArray *buttons = @[_pastButton, _deleteButton, _breakButton, _inputButton];
    for (NSInteger i = 0; i < buttons.count-1; i++) {
        UIButton *button1 = buttons[i];
        UIButton *button2 = buttons[i+1];
        
        [button2.topAnchor constraintEqualToAnchor:button1.topAnchor].active = YES;
        [button2.leftAnchor constraintEqualToAnchor:button1.rightAnchor constant:10].active = YES;
        [button2.heightAnchor constraintEqualToAnchor:button1.heightAnchor].active = YES;
        [button2.widthAnchor constraintEqualToAnchor:button1.widthAnchor].active = YES;
    }

0x02 代码区别

图 1 的代码,是在最后一步添加,最后一个按钮,的右侧约束

        if (i == buttons.count-1) {
            [button2.rightAnchor constraintEqualToAnchor:_textView.rightAnchor].active = YES;
        }

图 2 的代码,是在开始添加,最后一个按钮,的右侧约束

        [_inputButton.rightAnchor constraintEqualToAnchor:_textView.rightAnchor].active = YES;

可见,
约束设置的顺序,是多么滴重要!


0x03 我的小作品

欢迎体验我的作品之一:小五笔 86 版
五笔学习好帮手
App Store 搜索即可~


你可能感兴趣的:(iOS,iOS各种报错,ios,cocoa,macos)