2

I have a UITextView to display the title and content of an article. Here is my code:

static func setTextViewRichText(textView: UITextView, html: String, title: String) {

    do {
        let titleText = NSAttributedString(string: title + "\n", attributes: [NSFontAttributeName: UIFont(name: "Helvetica", size: 20)!])
        let contentText = try NSAttributedString(data: html.dataUsingEncoding(NSUTF8StringEncoding)!, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: NSNumber(unsignedLong: NSUTF8StringEncoding)], documentAttributes: nil)
        let text = NSMutableAttributedString(attributedString: titleText)
        text.appendAttributedString(contentText)
        textView.attributedText = text

    } catch let err as NSError {
        NSLog("%s", err)
        textView.text = title + "\n" + html
    }
}

The initial scroll position is not 0, which is not what I desired. I didn't set any properties in code.

OMGPOP
  • 1,995
  • 8
  • 52
  • 95
  • A UITextView inherits from UIScrollView, take a look here: http://stackoverflow.com/questions/9450302/get-uiscrollview-to-scroll-to-the-top – Fred Faust Jan 05 '16 at 00:11

1 Answers1

0

Try to layout first:

textView.layoutIfNeeded()
textView.attributedText = myText

Or you can reset the scrolling offset:

textView.attributedText = myText
textView.contentOffset = .zero
Cœur
  • 37,241
  • 25
  • 195
  • 267