我正在使用UITextView在ViewDidLoad()中显示长文本:
var story1 = "Researchers on Friday introduced the stunningly realistic-looking interactive humanoid robot to the world, and she reacted by nodding her head, squinting, moving her hand and eyeballs and telling assembled local photographers, with her speech synched to her lip movements, to snap her face from a more flattering angle. Girl's got spirit. \n\nJia Jia made her public debut at the University of Science and Technology of China, where she came to life over the course of three years. While her rosy cheeks and pink lips make her look like she has blood running through her actuators, she still has a way to go before she'll be confused with a human. Her expressions are currently limited to 'microexpressions' and her speech has that distinct stiffness that screams 'I am a robot and I will one day chase you from your home'\n\......." // a very long text with many rows
self.storyTextView.text = story1
如果我为storyTextView设置Scrolling Enabled
,则textview将显示不是从头开始的文本。我可以在文本的中间(或底部)看到滚动指示器。
我试过
self.storyTextView.scrollsToTop = true
但它没有帮助。
如果我取消选中Scrolling Enabled
,或者文本不是太长而无法在UITextView中显示整个文本,则会按预期从头开始显示。见截图2。
有没有办法从文本开头显示长文本(将滚动指示器移到顶部)?我检查了约束和布局,但似乎没有关系。我做了很多搜索但直到现在都没有运气。我可能会错过一些简单的设置,但任何人都可以帮助我。
答案 0 :(得分:5)
使用contentOffset
属性:
textView.contentOffset = CGPointZero
Swift 3的更新:
textView.contentOffset = CGPoint.zero
答案 1 :(得分:1)
试试这个:
self.storyTextView.scrollRangeToVisible(NSRange(location:0, length:0))
答案 2 :(得分:1)
唯一适用于iOS 11和swift 4的解决方法是 在viewDidLoad处设置滚动并在viewDidAppear处设置为ON。 它适用于UIScrollView和UiTextView。 经过测试的代码。
override func viewDidLoad() {
super.viewDidLoad()
scrollView.isScrollEnabled = false
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
scrollView.isScrollEnabled = true
}
答案 3 :(得分:0)
就我而言,此解决方案有效,Swift 4:
override func viewDidLayoutSubviews() {
self.txt_about.setContentOffset(CGPoint.zero, animated: false)
}
答案 4 :(得分:0)
在ViewController中添加以下方法
override public func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
textView.contentOffset = CGPoint.zero
}