如何调整 UIButton 的大小以适应文本而不使其比屏幕更宽?

How do I resize a UIButton to fit the text without it going wider than the screen?(如何调整 UIButton 的大小以适应文本而不使其比屏幕更宽?)
本文介绍了如何调整 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.

我已将换行设置为自动换行并尝试了 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 的大小以适应文本而不使其比屏幕更宽?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Pushing UIViewController above UITabBar(将UIView控制器推送到UITabBar上方)
java.lang.IllegalStateException: SimpleTypeImpl should not be created for error type(异常:不应为错误类型创建SimpleTypeImpl)
Android IllegalArgumentException: The tag for fragment_XXX is invalid. Received: layout-sw600dp/fragment_XXX_0(Android IlLegalArgumentException:Fragment_XXX的标签无效。收到:Layout-sw600dp/Fragment_XXX_0)
iOS convert audio sample rate from 16 kHz to 8 kHz(IOS将音频采样率从16 kHz转换为8 kHz)
Enforcing an audio sampling rate in iOS(在iOS中强制音频采样率)
HTTPS request using volley(使用 volley 的 HTTPS 请求)