0

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.

goal text view

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.

Jumpman987
  • 307
  • 1
  • 5
  • 17
  • Use a `UILabel` with `textAlignment = .center`? – beyowulf Jul 02 '18 at 19:23
  • My text is in a textview so using a UILabel wouldn't really fit well with what I'm trying to do. – Jumpman987 Jul 02 '18 at 19:28
  • What features of a `UITextView` are you using? – beyowulf Jul 02 '18 at 19:34
  • After setting the delegate for the text view I call either one of the methods above (the extension methods), that's it. – Jumpman987 Jul 02 '18 at 19:36
  • 1
    Right, but are you using scrolling, editing or selection? Otherwise you should replace your `UITextView` with a `UILabel` which is generally easier to work with when it comes to laying things out. Even if you are using one of those features, it might be easier to use a `UILabel` for the empty state and hide/show the `UITextView` when those features are in play. – beyowulf Jul 02 '18 at 19:39
  • Ok, main reason why I went with a text view was because I needed to allow the user to click on the text and edit it whenever they needed, but I guess I can look into adding a UILabel to center the text when not editing. – Jumpman987 Jul 02 '18 at 19:45
  • You could also just use a UITextField and center it in the middle of the container. – Nordeast Jul 02 '18 at 21:16
  • @Jumpman987 you should go with https://stackoverflow.com/a/41387780/8608650. – arpita Jul 03 '18 at 07:54

0 Answers0