1

I'm building up the textual content of a UITextView, by adding individual paragraphs one at a time to an NSMutableAttributedString. Some of these paragraphs need to be indented, as they are hierarchical, as in:

1. ...    
   (a). ... 
       (i). ...
       (ii). ...
   (b). ...
...

To (try to) do the indentation, I'm using this code:

let paraStyle = NSMutableParagraphStyle()
paraStyle.firstLineHeadIndent = CGFloat(indentLevel * 20)
paraStyle.headIndent = CGFloat(indentLevel * 20) 
attrText.addAttribute(.paragraphStyle, value: paraStyle, range:NSRange(location: 0, length: attrText.length))

and finally

textView.attributedText = attrText

where indentLevel indicates how much a given paragraph is to be indented.

When I look at the final attributed text in the debugger, I can see the correct paragraph styling is in place, but the text on-screen is NOT indented at all; everything is left-justified.

What am I missing/misunderstanding about styling paragraphs using attributed strings in a UITextView?

randallmeadows
  • 833
  • 1
  • 10
  • 19
  • Do you intend on editing the text? just a thought that it would have been easier with a UILabel? – Sean Lintern May 07 '19 at 14:15
  • No, it will be display-only (non-editable, but selectable). I chose the UITextView because there will be custom links within the text, and UITextView gives me that functionality for free. – randallmeadows May 07 '19 at 15:51
  • I'm curious, though, how you think UILabel would be any different/easier, in terms of my question, than UITextView? – randallmeadows May 07 '19 at 15:52
  • Care to post your string as well. Where you create the attributed text – agibson007 May 07 '19 at 16:38
  • It's dynamic text, a series of plain ol' Strings read in from Core Data, each instance a single paragraph; one or more of these paragraphs are concatenated together to form the on-screen display. – randallmeadows May 07 '19 at 21:05
  • This is essentially the code that does that: let attrText = NSMutableAttributedString() let count = paragraphs.count for i in 0.. 0 { // Need an extra terminating space, because of aa apparent bug in NSMutableAttributedString: let formatted: NSMutableAttributedString = format("\(text) ", indentLevel: Int(paragraph.indent)) attrText.append(formatted) if i < count-1 { attrText.append(NSMutableAttributedString(string: "\n")) } } } followed by the code in my original post. – randallmeadows May 07 '19 at 21:06
  • The format() method applies a font to the entire range, and then seeks out and inserts custom URL links. – randallmeadows May 07 '19 at 21:09
  • Sorry for the late response, I would have thought a UILabel would be more likely to stick to your paragraph style, it sounds like the textview is overriding paragraphstyle – Sean Lintern May 08 '19 at 09:50

0 Answers0