ContentOffset does nothing for the UITextView the first time

I am trying to get a UIViewController to display some text vertically in a UITextView. When the application starts up, the text is aligned upward. But if I try to select some text, the text then moves to the center vertically. It looks like the contentOffset setting doesn't do anything the first time, unless there is any action to trigger it to reconfigure the layout (like text selection in my script).

Also when I register the values ​​for height, size, contentHeight and topCorrect, the values ​​of the first call are the same as the second call. So I get the same value, but the UITextView somehow doesn't respond to contentOffset the first time.

I even tried to move logic to viewDidLayoutSubviews () and viewDidAppear (). I had the same result. So I don't think the problem is that the logic is in the wrong place.

I think some people have had success with it on iOS 7 and Obj-C. I am trying to run it on iOS 8 and Swift.

Any suggestion or help would be much appreciated.

class PageContentViewController: UIViewController {

@IBOutlet weak var textView: UITextView!

override func viewWillLayoutSubviews() {
    super.viewWillLayoutSubviews()
    self.textView.textContainerInset = UIEdgeInsetsMake(0, 16.0, 0, 16.0)
    let height = self.textView.bounds.size.height
    let size = CGSizeMake(self.textView.frame.width, CGFloat.max)
    var contentHeight = self.textView.sizeThatFits(size).height
    var topCorrect = (height - contentHeight * self.textView.zoomScale) / 2.0
    topCorrect = topCorrect < 0.0 ? 0.0 : topCorrect;
    self.textView.setContentOffset(CGPointMake(0, -topCorrect), animated: false)
}

      

}

+3


source to share





All Articles