我有一个UIlabel的numberOfLines为2
和lineBreakMode =截头
但是当我运行它
而不是像第一行那样截断头
...1st Line Content
2nd Line Content
截断像
1st Line Content
...2nd Line Content
如何在第一行本身中截断标签的开头?
最佳答案
试试这个在Swift 3
中测试过的代码
let text = "Hello World! Hello World! Hello World! Hello World! "
let attString = NSMutableAttributedString(string: text)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .left
paragraphStyle.firstLineHeadIndent = 0
paragraphStyle.headIndent = 40 // set any vallue
paragraphStyle.lineBreakMode = .byTruncatingHead
attString.addAttribute(NSParagraphStyleAttributeName, value:paragraphStyle, range:NSMakeRange(0, attString.length))
attString.addAttribute(NSFontAttributeName, value: UIFont(name: "Arial", size: 25)!, range: NSMakeRange(0, attString.length))
label.attributedText = attString // label is your UILabel
label.numberOfLines = 2
输出1:
paragraphStyle.firstLineHeadIndent = 40 // set any vallue
paragraphStyle.headIndent = 0
输出2:
更新:可以通过组合两个属性字符串来实现
let dotAttributes = [NSForegroundColorAttributeName: UIColor.red, NSFontAttributeName: UIFont(name: "Arial", size: 25)]
let textAttributes = [NSForegroundColorAttributeName: UIColor.red, NSFontAttributeName: UIFont(name: "Arial", size: 25)]
let dotString = NSMutableAttributedString(string: ". . . ", attributes: dotAttributes)
let textString = NSMutableAttributedString(string: "Hello World! Hello World! Hello World! Hello World!", attributes: textAttributes)
let totalString = NSMutableAttributedString()
totalString.append(dotString)
totalString.append(textString)
label.numberOfLines = 2
label.attributedText = totalString
注意:可以使用paragraphStyle(headIndent)创建左边距。
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .left
paragraphStyle.firstLineHeadIndent = 5
paragraphStyle.headIndent = 5 // set any vallue
paragraphStyle.lineBreakMode = .byTruncatingHead
totalString.addAttribute(NSParagraphStyleAttributeName, value:paragraphStyle, range:NSMakeRange(0, totalString.length))
输出:
关于ios - 用2行截断UILabel的头,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40716727/