Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSAttributedString with tabs

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

enter image description here

like image 274
Hebbian Avatar asked Aug 11 '15 15:08

Hebbian


1 Answers

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

Screenshot of label rendering the above attributed string

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.

like image 151
Brian Nickel Avatar answered Sep 18 '22 20:09

Brian Nickel