如何调整UIButton的大小以适应文本,而不会超出屏幕范围? [英] How do I resize a UIButton to fit the text without it going wider than the screen?

查看:125
本文介绍了如何调整UIButton的大小以适应文本,而不会超出屏幕范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个UIButton,我想调整大小以适应其中的任何文本。它的设置宽度为280,但文本应该换行到下一行,并根据需要扩展按钮的高度。

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 the button as needed.

我已设置行打破Word Wrap并尝试使用sizeToFit但只会使按钮变宽,而不是垂直。

I've set line breaks to Word Wrap and tried sizeToFit but that only makes the button go wider, not vertical.

推荐答案

我设法让它工作在UIButton类别中:

I managed to get it working in a category of UIButton:

@interface UIButton (ExpandsVertically)

- (CGSize)sizeThatFits:(CGSize)size;

@end

@implementation UIButton (Expandable)

- (CGSize)sizeThatFits:(CGSize)size {

    // for the width, I subtract 24 for the border
    // for the height, I use a large value that will be reduced when the size is returned from sizeWithFont
    CGSize tempSize = CGSizeMake(size.width - 24, 1000);

    CGSize stringSize = [self.titleLabel.text
                         sizeWithFont:self.titleLabel.font
                         constrainedToSize:tempSize
                         lineBreakMode:UILineBreakModeWordWrap];

    return CGSizeMake(size.width - 24, stringSize.height);
}

@end

如果有人使用这个,请确保设置:

If anyone uses this make sure to set:

myButton.titleLabel.lineBreakMode = UILineBreakModeWordWrap;

这篇关于如何调整UIButton的大小以适应文本,而不会超出屏幕范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆