我正在尝试制作一个 UIButton
,它的 titleLabel 中有两行文本。这是我正在使用的代码:
UIButton *titleButton = [[UIButton alloc] initWithFrame:CGRectMake(15, 10, frame.size.width-100, 100)];
titleButton.titleLabel.font = [UIFont boldSystemFontOfSize:24.0];
[titleButton setTitle:@"This text is very long and should get truncated at the end of the second line" forState:UIControlStateNormal];
titleButton.titleLabel.lineBreakMode = UILineBreakModeTailTruncation;
titleButton.titleLabel.numberOfLines = 2;
[self addSubview:titleButton];
当我尝试这个时,文本只出现在一行上。似乎在 UIButton.titleLabel
中实现多行文本的唯一方法是设置 numberOfLines=0
并使用 UILineBreakModeWordWrap
。但这并不能保证文本正好是两行。
不过,使用纯 UILabel
确实有效:
UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 10, frame.size.width-100, 100)];
titleLabel.font = [UIFont boldSystemFontOfSize:24.0];
titleLabel.text = @"This text is very long and should get truncated at the end of the second line";
titleLabel.numberOfLines = 2;
titleLabel.lineBreakMode = UILineBreakModeTailTruncation;
[self addSubview:titleLabel];
有谁知道如何让 UIButton
使用两行代码?是创建单独的 UILabel
来保存文本并将其添加为按钮的 subview 的唯一解决方案吗?
最佳答案
您不需要向 UIButton 添加 UILabel。这只是额外的对象和工作。
在按钮的 titleLabel 上设置这些属性。
button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
button.titleLabel.numberOfLines = 2;//if you want unlimited number of lines put 0
swift :
button.titleLabel!.lineBreakMode = NSLineBreakMode.ByWordWrapping
button.titleLabel!.numberOfLines = 2//if you want unlimited number of lines put 0
https://stackoverflow.com/questions/7831928/
相关文章:
ios - UITableView 中的圆形 UIImageView 没有性能影响?
ios - 在自动布局中将 subview 的 X 居中抛出 "not prepared for t
objective-c - Xcode 不断要求输入密码以使用系统钥匙串(keychain)
objective-c - 在 Objective-C 中将所有文本转换为小写
objective-c - 如何使用 AFNetworking 设置超时
objective-c - sizeWithFont 方法已弃用。 boundingRectWith
objective-c - 我不想在开始更新、结束更新 block 中为 uitableview 设