让我们看看我有一个这样的字符串:

NSString *longStr = @"AAAAA\nBBBBB\nCCCCC";  

如何使UILabel像这样显示消息

五星级 BBBBB CCCCC

我不认为\n能被UILabel识别,我能在NSString中放入什么东西让UILabel知道它必须在那里创建换行符吗?


当前回答

在Swift 2.2, > iOS 8

我在Storyboard的属性检查器下设置Lines = 0,并将引用出口链接到标签。然后在控制器中像这样使用:

 @IBOutlet weak var listLabel: UILabel!

 override func viewDidLoad() {
      ...
      listLabel.text = "Line 1\nLine 2\nLine 3\nLine 4\nLine 5\nLine 6\nLine 7\nLine 8"
 }

其他回答

如果你将可用属性从普通设置为有属性…UILabel将保存多行文本,无论你的UILabel高度和宽度设置为适合你想要显示文本的屏幕区域。

在Interface Builder中的小框中输入时使用option-return插入换行(\n)。在Interface Builder的Label属性中,设置# Lines = 0。

选择标签,然后将Lines属性更改为0,如上图所示,然后在字符串中使用\n作为换行符。

在Xcode 6上,我可以在swift编程上使用\n没有问题

在Swift 2.2, > iOS 8

我在Storyboard的属性检查器下设置Lines = 0,并将引用出口链接到标签。然后在控制器中像这样使用:

 @IBOutlet weak var listLabel: UILabel!

 override func viewDidLoad() {
      ...
      listLabel.text = "Line 1\nLine 2\nLine 3\nLine 4\nLine 5\nLine 6\nLine 7\nLine 8"
 }

重要的是要注意它是\n(反斜杠)而不是/n。