使用自动布局向UIButton添加边框

时间:2014-09-08 17:38:38

标签: objective-c uibutton autolayout

我有自定义UIView。在init方法中,我添加了一个按钮,并希望添加一个顶部红色边框。我也尝试使用自动布局执行此操作,但在运行控制台时告诉我它无法满足所有约束。我在俯瞰什么?

- (id)init {
    self = [super init];
    if (self) {

        _button = [[UIButton alloc] init];

        UIView *border = [[UIView alloc] init];
        border.backgroundColor = [UIColor redColor];
        [_button addSubview:border];

        [_button addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[border]|"
                                                                        options:0 metrics:0 views:NSDictionaryOfVariableBindings(border)]];
        [_button addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[border(1)]"
                                                                        options:0 metrics:0 views:NSDictionaryOfVariableBindings(border)]];
        [self addSubview:_button];

        [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_button(35)]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_button)]];
        [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[_button(35)]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_button)]];

    }
    return self;
}

这是控制台消息:

Unable to simultaneously satisfy constraints.
Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints) 
(
    "<NSLayoutConstraint:0x79f73ce0 H:|-(0)-[UIView:0x79f72ec0]   (Names: '|':UIButton:0x79f72900 )>",
    "<NSLayoutConstraint:0x79f73d10 H:[UIView:0x79f72ec0]-(0)-|   (Names: '|':UIButton:0x79f72900 )>",
    "<NSLayoutConstraint:0x79f73b40 H:[UIButton:0x79f72900(35)]>",
    "<NSAutoresizingMaskLayoutConstraint:0x79f327c0 h=--& v=--& UIView:0x79f72ec0.midX ==>"
)

Will attempt to recover by breaking constraint 
<NSLayoutConstraint:0x79f73d10 H:[UIView:0x79f72ec0]-(0)-|   (Names: '|':UIButton:0x79f72900 )>

由于

1 个答案:

答案 0 :(得分:0)

这一行:

    "<NSAutoresizingMaskLayoutConstraint:0x79f327c0 h=--& v=--& UIView:0x79f72ec0.midX ==>"

表示自动调整掩码被隐式添加到border,这被转换为冲突的自动布局约束。

translatesAutoresizingMaskIntoConstraints设置为NO可以解决问题:

UIView *border = [[UIView alloc] init];
border.translatesAutoresizingMaskIntoConstraints = NO