我有如下代码... 编程
UILabel *buttonLabel = [[UILabel alloc] initWithFrame:targetButton.bounds]; buttonLabel.text = @"Long text string"; [targetButton addSubview:buttonLabel]; [targetButton bringSubviewToFront:buttonLabel];
...这个想法是我能够为按钮添加多行文本,可是该文本始终被UIButton的backgroundImage遮盖。 显示该按钮的子视图的日志记录调用代表已添加UILabel,但看不到文本自己。 这是UIButton中的错误仍是我作错了什么? app
对于使用Xcode 4故事板的用户,能够单击按钮,而后在Attributes Inspector下的Utilities窗格的右侧,将看到一个Line Break选项。 选择自动换行,您应该一切顺利。 布局
对于IOS 6: spa
button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping; button.titleLabel.textAlignment = NSTextAlignmentCenter;
如 日志
UILineBreakModeWordWrap and UITextAlignmentCenter
从IOS 6开始不推荐使用。 code
有一种更简单的方法: get
someButton.lineBreakMode = UILineBreakModeWordWrap;
(针对iOS 3及更高版本进行编辑:) string
someButton.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
这里的答案告诉您如何以编程方式实现多行按钮标题。 it
我只是想补充一下,若是您使用情节提要,则能够键入[Ctrl + Enter]来在按钮标题字段上强制换行。 方法
高温超导
若是在iOS 6上使用自动布局,则可能还须要设置preferredMaxLayoutWidth
属性:
button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping; button.titleLabel.textAlignment = NSTextAlignmentCenter; button.titleLabel.preferredMaxLayoutWidth = button.frame.size.width;