带有选项卡的NSAttributedString

时间:2015-08-11 15:00:26

标签: ios objective-c nsattributedstring

如何使用这种文字格式创建UILabel?你会使用NSAttributedString吗?

enter image description here

2 个答案:

答案 0 :(得分:19)

NSAttributedString可以创建带制表位的文本列。这类似于在具有相同限制的文字处理器中完成的操作。

let text = "Name\t: Johny\nGender\t: Male\nAge\t: 25\nFavourites\t: Reading, writing"

let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.tabStops = [NSTextTab(textAlignment: NSTextAlignment.Left, location: 150, options: [:])]
paragraphStyle.headIndent = 150

label.attributedText = NSAttributedString(string: text, attributes: [NSParagraphStyleAttributeName: paragraphStyle])
  

Screenshot of label rendering the above attributed string

tabStops提供每个标签后继续发送文字的位置。在这里,我们在第一列之后的合理点处做了一个选项卡。 headIndent告诉标签包装的文本需要缩进固定的数量,因此它将换行到下一行。

这种方法的局限性是:

  1. 制表位位置是一个固定点值,因此您需要知道自己想要什么。如果您选择的值小于某些行的第一列的宽度,则这些行将缩进到其他位置。
  2. 只有当您的最后一列是包装的列时,才能真正包装。由于您的第二列以“:”开头,您可能只想增加headIndent或将“:”拆分为\t:\t并设置第二个制表位。如果你不让文本换行,这不是问题。
  3. 如果这些限制过于严格,您可以将标签重组为具有自动布局限制的多个标签的集合。

答案 1 :(得分:1)

在Swift 4.2或更高版本中

let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.tabStops = [NSTextTab.init(textAlignment: .left, location: 150, options: [:])]
paragraphStyle.headIndent = 150

let attributedTitle = NSAttributedString(string: "Some Title", attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14.0), NSAttributedString.Key.paragraphStyle: paragraphStyle])