问题
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.
回答1:
Try to layout first:
textView.layoutIfNeeded()
textView.attributedText = myText
Or you can reset the scrolling offset:
textView.attributedText = myText
textView.contentOffset = .zero
来源:https://stackoverflow.com/questions/34602155/uitextview-initial-scroll-position-is-not-0