How to align text inside textView vertically?

I want to vertically align the text inside my UITextView (so that it will be in the middle). How can i achieve this? I looked up and could not find an answer that could help me.

Thanks in advance.

+16
source share
2 answers

Link the text view to your viewcontroller and name it whatever you want (say, textView).

In the viewDidLayoutSubviews function viewDidLayoutSubviews insert this line:

 textView.centerVertically() 

Then, under the last brace of your class, put this extension:

  extension UITextView { func centerVertically() { 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 } } 

To use this function for swift2 , just change CGFloat.greatestFiniteMagnitude to CGFloat.max

+33
source

If you want to do this with a storyboard, you can add a view inside your textView. Then set the limits that you used for textView for the new view. Finally, add the following restrictions to the text view:

  • (left and right) O and point to a new view
  • using alignment constraints, add a vertical constraint.

    enter image description here

+1
source

Source: https://habr.com/ru/post/1013615/


All Articles