Multiline UIButton and autolayout

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

I have created a view controller that looks like this:

\"enter

I want the two

16条回答
  •  盖世英雄少女心
    2020-12-03 14:06

    I had the same problem where I wanted my button to grow along with its title. I had to sublcass the UIButton and its intrinsicContentSize so that it returns the intrinsic size of the label.

    - (CGSize)intrinsicContentSize
    {
        return self.titleLabel.intrinsicContentSize;
    }
    

    Since the UILabel is multiline, its intrinsicContentSize is unknown and you have to set its preferredMaxLayoutWidth See objc.io article about that

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

    The rest of the layout should work. If you set your both button having equal heights, the other one will grow to. The complete button looks like this

    @implementation TAButton
    
    - (instancetype)initWithCoder:(NSCoder *)coder
    {
        self = [super initWithCoder:coder];
        if (self) {
            self.titleLabel.numberOfLines = 0;
            self.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
        }
        return self;
    }
    
    - (CGSize)intrinsicContentSize
    {
        return self.titleLabel.intrinsicContentSize;
    }
    
    - (void)layoutSubviews
    {
        [super layoutSubviews];
        self.titleLabel.preferredMaxLayoutWidth = self.titleLabel.frame.size.width;
        [super layoutSubviews];
    }
    
    @end
    

提交回复
热议问题