I've been trying unsuccessfully to vertically center my text in my UITextView as soon as my app starts up. No matter what I've tried the text just appears at the top of the text view like it normally would. Here is a photo.
The only time the text centers correctly is when I type it, this was done by using an observer. Here is the code I'm using to center my text in viewDidLoad, I've tried 2 methods, neither worked.
extension UITextView {
func centerText() {
self.textAlignment = .center
let fittingSize = CGSize(width: bounds.width, height: CGFloat.greatestFiniteMagnitude)
let size = sizeThatFits(fittingSize)
let topOffset = (bounds.size.height - size.height * zoomScale) / 2
let positiveTopOffset = max(1, topOffset)
contentOffset.y = -positiveTopOffset
}
func alignTextVerticallyInContainer() {
var topCorrect = (self.bounds.size.height - self.contentSize.height * self.zoomScale) / 2
topCorrect = topCorrect < 0.0 ? 0.0 : topCorrect;
self.contentInset.top = topCorrect
}
}
I would call these methods in my viewDidLoad like this: self.goalTextView.centerText()
or self.goalTextView.alignTextVerticallyInContainer()
. So now that you've seen what I've tried so far, anyone have any idea how to force the text in the textview to be centered vertically on startup? Any help would be appreciated.