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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27762236/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 04:13:52  来源:igfitidea点击:

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

iosiphoneswiftuilabel

提问by tika

By selecting a Label in a StoryBoard, I can select Line Breakto be Word Wrapand change number of lines to be more than 1. How can I do that Programmatically in Swift?enter image description here

通过在 StoryBoard 中选择一个标签,我可以选择Line BreakWord Wrap行数更改为大于 1。如何在 Swift 中以编程方式执行此操作?在此处输入图片说明

回答by rakeshbs

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

回答by Zoran777

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.

请记住在“CGRectMake(7, 200, 370, 100)”中         增加高度<--
否则标签将无法采用多行文本。

回答by swiftBoy

Note with Swift 3you need to use updated method byWordWrapping

注意Swift 3你需要使用更新的方法 byWordWrapping

productNameLabel.lineBreakMode = .byWordWrapping
productNameLabel.numberOfLines = 1

enter image description here

在此处输入图片说明



Or for adding Ellipsisat the end use byTruncatingTail

或者在最后使用TruncatingTail添加省略号

productNameLabel.lineBreakMode = .byTruncatingTail
productNameLabel.numberOfLines = 1

enter image description here

在此处输入图片说明