我在试着做一个UIButton,它的标题标签里有两行文字.这是我使用的代码:

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];

当我try 这样做时,文本只出现在一行上.似乎在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来保存文本,并将其添加为按钮的子视图吗?

推荐答案

Updated answer for more recent iOS versions

既然这是公认的答案,请在这里添加@Sean的答案:

在按钮的title Label上设置这些属性.

button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
button.titleLabel.numberOfLines = 2; // if you want unlimited number of lines put 0

SWIFT 3和4:

button.titleLabel?.lineBreakMode = .byWordWrapping
button.titleLabel?.numberOfLines = 2 // if you want unlimited number of lines put 0

Original answer for an older version of iOS

如果你想在UIButton的基础上加上2行文字,你应该在上面加一个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;
[myButton addSubview:titleLabel]; //add label to button instead.

Updated for interface builder solution

添加了@Borut Tomazin的答案,以获得更完整的答案.

您可以更轻松地完成这项工作,不需要代码.在接口生成器中,将UIButton上的Line Break设置为Word Wrap.然后您可以插入多行标题.刚按了Option + Return键就可以做新台词了.您还需要将其添加到界面生成器中的用户定义的运行时属性中:

titleLabel.textAlignment Number [1]

Ios相关问答推荐

为什么controlSize属性在SwiftUI中不起作用?

如何在SwiftUI中扩展 colored颜色 超出顶部边缘

UIBezierPath包含:方法不检测到厚度大于1像素的线上的touch

避免从CoreData加载图像列表时出现SwiftUI挂起

滚动时突出显示工具栏项目

磁盘上的Objective-C ISA指针与实例化对象时的比较

SwiftUI-工作表不显示导航标题

ITMS-90432:将应用上传到应用store 时出现问题

应用程序被杀死时如何在 flutter ios 应用程序中播放音频?

SwiftUI 图表 BarMark 将注释对齐到图表顶部

视图之间的 SwiftUI 过渡,没有过渡

如何在Collection 后更改并保留按钮 colored颜色 ,然后在 SwiftUI 中切换回来?

如何在 Swift 中旋转 UIButton 和 UILabel 的文本?

Xcode 缺少支持文件 iOS 12.2 (16E227)

在 iPhone 中将 UIViewController 显示为弹出窗口

刷新由 Xcode 7 管理的团队配置文件中的设备?

SwiftUI NavigationView navigationBarTitle LayoutConstraints 问题

如何从 UIPickerView 获取选定的值

使用 Swift 在一个 ViewController 中强制横向模式

Objective-C 将 NSDate 设置为当前 UTC