NSAttributedString with tabs

♀尐吖头ヾ 提交于 2020-01-03 08:20:27

问题


How do you create a UILabel with this kind of text format? Would you use NSAttributedString?


回答1:


NSAttributedString can create text columns with tab stops. This is similar to how it is done in a word processor with the same limitations.

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

tabStops provides point positions for where to continue text after each tab. Here we did one tab at a reasonable point after the first column. headIndent tells the label that wrapped text needs to be indented by a fixed amount, so it wraps to the next line.

The limitations with this approach are:

  1. The tab stop location is a fixed point value so you need to know what you want. If the value you pick is less than the width of the first column for some lines, those lines will indent to a different location.
  2. Wrapping only really works if your last column is the one that wraps. Since your second column was prefaced by ":" You may want to either just increase your headIndent or also split out the ":" to be \t:\t and set up a second tab stop. If you're not letting text wrap, this is not an issue.

If these limitations are too restrictive, you can restructure your label to be a collection of multiple labels with auto layout constraints.




回答2:


In Swift 4.2 or above

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


来源:https://stackoverflow.com/questions/31945333/nsattributedstring-with-tabs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!