简体   繁体   English

Swift标签中的换行符和行数(以编程方式)

[英]Line Breaks and Number of Lines in Swift Label (Programmatically)

By selecting a Label in a StoryBoard, I can select Line Break to be Word Wrap and change number of lines to be more than 1. How can I do that Programmatically in Swift? 通过在StoryBoard中选择一个标签,我可以将Word Wrap Line Break选择为“自动Word Wrap Line Break ,并将行数更改为大于1。我该如何在Swift中以编程方式做到这一点? 在此处输入图片说明

You can do this to set it programmatically 您可以执行此操作以编程方式进行设置

 label.lineBreakMode = NSLineBreakMode.ByWordWrapping
 label.numberOfLines = 3

Swift 3/4 迅捷3/4

label.lineBreakMode = .byWordWrapping
label.numberOfLines = 3

If you want the label to have multiple lines, do this: 如果您希望标签有多行,请执行以下操作:

var myLabel:UILabel = UILabel(frame: CGRectMake(7, 200, 370, 100))
myLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping
myLabel.numberOfLines = 0                      //'0' means infinite number of lines

Do remember to increase the height in "CGRectMake (7, 200, 370, 100 )" <-- This 记得以增加高度 “CGRectMake(7,200,370,100)”< -这
Otherwise the label won't be able to take the multiple lines of text. 否则,标签将无法采用多行文本。

Note with Swift 3 you need to use updated method byWordWrapping 请注意,在Swift 3中,您需要使用WordWrapping更新的方法

productNameLabel.lineBreakMode = .byWordWrapping
productNameLabel.numberOfLines = 1

在此处输入图片说明


Or for adding Ellipsis at the end use byTruncatingTail 或者在最终使用byTruncatingTail时添加省略号

productNameLabel.lineBreakMode = .byTruncatingTail
productNameLabel.numberOfLines = 1

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM