用2行截断UILabel的头部

我有一个UI的标签numberOfLines为2和lineBreakMode =截断头

但是当我运行它而不是像第一行截断头

...1st Line Content 2nd Line Content 

它截断像

  1st Line Content ...2nd Line Content 

我如何在第一行截断标签的头部?

试试这个代码在Swift 3testing

  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:

在这里输入图像说明

更新:可以通过combain两个属性string来实现

  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)创build左边距。

  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)) 

输出:

在这里输入图像说明