How do I resize a UIButton to fit the text without it going wider than the screen?(如何调整 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 的大小以适应文本而不使其比屏幕更宽?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何调整 UIButton 的大小以适应文本而不使其比屏幕更宽?
- Xcode 7.3 中带有 UILabel 的 UIStackView 2022-01-01
- 如何在 iPhone 模拟器中重置 NSUserDefaults 数据? 2022-01-01
- GPS状态的广播接收器? 2022-01-01
- UITextView 内容插图 2022-01-01
- SetOnItemSelectedListener上的微调程序错误 2022-01-01
- 在 Iphone SDK 的导航栏上添加多个按钮 2022-01-01
- 网上有没有好的 UIScrollView 教程? 2022-01-01
- 类似于 Mail.app 的 iPad 模态视图控制器? 2022-01-01
- URL编码Swift iOS 2022-01-01
- 使用自动布局向 UIScrollView 添加动态大小的视图 2022-01-01