Multiline UIButton and autolayout

后端 未结 16 1496
无人共我
无人共我 2020-12-03 13:08

I have created a view controller that looks like this:

\"enter

I want the two

16条回答
  •  情歌与酒
    2020-12-03 13:41

    There is a solution without subclassing on iOS11. Just need to set one additional constraint in code to match height of button and button.titleLabel.

    ObjC:

    // In init or overriden updateConstraints method
    NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:self.button
                                                                  attribute:NSLayoutAttributeHeight
                                                                  relatedBy:NSLayoutRelationEqual
                                                                     toItem:self.button.titleLabel
                                                                  attribute:NSLayoutAttributeHeight
                                                                 multiplier:1
                                                                   constant:0];
    
    [self addConstraint:constraint];
    

    And in some cases (as said before):

    - (void)layoutSubviews {
        [super layoutSubviews];
    
        self.button.titleLabel.preferredMaxLayoutWidth = CGRectGetWidth(self.button.titleLabel.frame);
    }
    

    Swift:

    let constraint = NSLayoutConstraint(item: button,
                                        attribute: .height,
                                        relatedBy: .equal,
                                        toItem: button.titleLabel,
                                        attribute: .height,
                                        multiplier: 1,
                                        constant: 0)
    
    self.addConstraint(constraint)
    

    +

    override func layoutSubviews() {
        super.layoutSubviews()
    
        button.titleLabel.preferredMaxLayoutWidth = button.titleLabel.frame.width
    }
    

提交回复
热议问题