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

南笙酒味 提交于 2020-07-16 16:29:19

问题


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?enter image description here


回答1:


You can do this to set it programmatically

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

Swift 3/4

label.lineBreakMode = .byWordWrapping
label.numberOfLines = 3



回答2:


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
Otherwise the label won't be able to take the multiple lines of text.




回答3:


Note with Swift 3 you need to use updated method byWordWrapping

productNameLabel.lineBreakMode = .byWordWrapping
productNameLabel.numberOfLines = 1


Or for adding Ellipsis at the end use byTruncatingTail

productNameLabel.lineBreakMode = .byTruncatingTail
productNameLabel.numberOfLines = 1



来源:https://stackoverflow.com/questions/27762236/line-breaks-and-number-of-lines-in-swift-label-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!