我有一个UIlabel,其numberOfLines为2 和lineBreakMode = Truncate Head
但是当我跑的时候 而不是像第一行那样在第一行截断头部
...1st Line Content
2nd Line Content
它像
一样截断 1st Line Content
...2nd Line Content
如何在第一行中截断标签的头部?
答案 0 :(得分:1)
尝试在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))
输出: