UITextView initial scroll position is not 0

烈酒焚心 提交于 2019-12-12 20:35:40

问题


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

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