UITextView初始滚动位置不为0

时间:2016-01-05 00:07:30

标签: ios swift uikit

我有一个UITextView来显示文章的标题和内容。这是我的代码:

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
    }
}

初始滚动位置不是0,这不是我想要的。我没有在代码中设置任何属性。

1 个答案:

答案 0 :(得分:0)

首先尝试布局:

textView.layoutIfNeeded()
textView.attributedText = myText

或者您可以重置滚动偏移:

textView.attributedText = myText
textView.contentOffset = .zero