ios - 带有换行和自动布局的 UIButton

标签 ios uibutton autolayout line-breaks

我有一个 UIButton ,我在应用程序中设置了它的文本,但是文本太长所以我想让 UIButton 文本做一个换行符和继续下一行。

而且它必须与 AutoLayout 配合使用。

我已经设法用 UILabel 和这段代码做到了这一点:

label.numberOfLines = 0;
label.preferredMaxLayoutWidth = 300.0;

但是当我将它应用到这样的按钮时:

button.titleLabel.preferredMaxLayoutWidth = 200.0;
button.titleLabel.numberOfLines = 0;

好像不行。

该代码放置在 viewDidLoad 中,如下所示:

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
label.numberOfLines = 0;
label.preferredMaxLayoutWidth = 300.0;

button.titleLabel.preferredMaxLayoutWidth = 200.0;
button.titleLabel.numberOfLines = 0; }

然后我像这样用 IBAction 设置按钮文本

-(IBAction)labelMake:(id)sender {

label.text = [NSString stringWithFormat: @"Test to see if label linebreaks"];

button.titleLabel.text = [NSString stringWithFormat: @"Test to see if button text linebreaks"];}

最佳答案

只需设置UIButton:

button.titleLabel.numberOfLines = 0;
button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;

并设置文本:

[button setTitle:@"This is a long text \nspanning multiple lines\nAnd there would be A LOT MORE" forState:UIControlStateNormal];

关于ios - 带有换行和自动布局的 UIButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29831040/

相关文章:

iOS:是否有一种标准方法来检查用户是否与给定元素以外的其他 UI 元素进行交互?

objective-c - 如何找到数组的索引?

iOS UIbutton奇怪的底部边缘

ios - 自动布局约束 : How to make a view maintains its width/height ratio when resized?

ios - 如何在 Swift 5 中将电子表格数据预加载到 Core Data?

ios - OpenGL ES GLKBaseEffect 与更改顶点位置

ios - 显示 searchResultsController 时出现 UISearchBar AutoLayout 错误

ios - Xcode 6 在更新 iPhone 6/6+ 时显示 iPhone 5 分辨率?

ios - 如何通过点击 UITextView ios 中的返回键来创建新行

ios - FirebaseAuth UI Google SignIn 在 iOS 上启用 cookie