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 的大小以适应文本而不使其比屏幕更宽?
基础教程推荐
- 如何将图像从一项活动发送到另一项活动? 2022-01-01
- iOS - UINavigationController 添加多个正确的项目? 2022-01-01
- SwiftUI-ScrollViewReader的ScrollTo不滚动 2022-01-01
- 如何比较两个 NSDate:哪个是最近的? 2022-01-01
- 为什么姜饼模拟器方向卡在应用程序中? 2022-01-01
- UIImage 在开始时不适合 UIScrollView 2022-01-01
- Play 商店的设备兼容性问题 2022-01-01
- navigationItem.backBarButtonItem 不工作?为什么上一个菜单仍然显示为按钮? 2022-01-01
- Xcode UIView.init(frame:) 只能在主线程中使用 2022-01-01
- Android Volley - 如何动画图像加载? 2022-01-01
