How do I resize a UIButton to fit the text without it going wider than the screen?

前端 未结 5 1672
耶瑟儿~
耶瑟儿~ 2020-12-14 17:55

I have a UIButton that I want to resize to fit whatever text is inside it. It has a set width of 280, but the text should wrap to the next line(s) and extend the height of

5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-14 18:34

    I've been facing a similar problem, had limited width for my buttons and wanted them to grow vertically, depending on the amount of text I'd give them. I ended up with a simple solution, based on what I've learnt in the Apple docs (https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/AutolayoutPG/ImplementingView/ImplementingView.html)

    I've subclassed UIButton and overridden two functions:

    - (void)setBounds:(CGRect)bounds {
        if (!CGRectEqualToRect(bounds, self.bounds)) {
            [self invalidateIntrinsicContentSize];
        }
        [super setBounds:bounds];
    }
    
    - (CGSize)intrinsicContentSize {
        //
        CGSize size;
    
        self.titleLabel.frame = CGRectMake(self.titleLabel.frame.origin.x,
                self.titleLabel.frame.origin.y,
                self.frame.size.width - self.contentEdgeInsets.left - self.contentEdgeInsets.right - self.titleEdgeInsets.left - self.titleEdgeInsets.right,
                0);
        size = [self.titleLabel sizeThatFits:self.titleLabel.frame.size];
        size = CGSizeMake(size.width, size.height + 20);
    
        return size;
    }
    

    What basically happens here is that the button invalidates its intrinsic size (only when the bounds set are actually new -- this is to prevent an endless loop), and when the system asks for the intrinsic content size, I recalculate that based on the width of the button. The extra 20px height is for padding. I've tried many other ways but since my layout is all based on AutoLayout, I wanted something that I don't have to update whenever the device rotates or so. This simply works.

    Good luck! Z.

提交回复
热议问题