Multiline UIButton and autolayout

后端 未结 16 1482
无人共我
无人共我 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:58

    @Jan's answer doesn't work for me in (at least) iOS 8.1, 9.0 with Xcode 9.1. The problem: titleLabel's -intrinsicContentSize returns very big width and small height as there is no width limit at all (titleLabel.frame on call has zero size that leads to measurements problem). Moreover, it doesn't take into account possible insets and/or image.

    So, here is my implementation that should fix all the stuff (only one method is really necessary):

    @implementation PRButton
    
    - (CGSize)intrinsicContentSize
    {
        CGRect titleFrameMax = UIEdgeInsetsInsetRect(UIEdgeInsetsInsetRect(UIEdgeInsetsInsetRect(
            self.bounds, self.alignmentRectInsets), self.contentEdgeInsets), self.titleEdgeInsets
        );
        CGSize titleSize = [self.titleLabel sizeThatFits:CGSizeMake(titleFrameMax.size.width, CGFLOAT_MAX)];
    
        CGSize superSize = [super intrinsicContentSize];
        return CGSizeMake(
            titleSize.width + (self.bounds.size.width - titleFrameMax.size.width),
            MAX(superSize.height, titleSize.height + (self.bounds.size.height - titleFrameMax.size.height))
        );
    }
    
    @end
    

提交回复
热议问题