George H George H - 9 months ago 41
iOS Question

UITextview text not centering vertically on initial view

I have an extension for UITextView which centers the text on a UITextView vertically that I found in the following SO answer:

My UITextView lives within a UITableViewCell, and the problem is that the function doesn't seem to work on the initial load. It only works when I reload the tableView or when I scroll.

I am calling the method within

but I have tried adding it to my custom cell class in
but have and no luck. Wondering if anyone has any other advice / solutions.


Also forgot to mention, my VC with the tableView is embedded in a navigationBar and tabBar. When I switch to a new VC in the tabBar and then back, the UITextView text realigns to the top incorrectly, even if it was centered already.


Answer Source

The correct place for sizing code in a view is UIView.layoutSubviews. Since your centering function depends on the bounds, you have to call it in layoutSubviews, otherwise the bounds may not be correct (ie they match whats in the nib and not the current device). You can call setNeedsLayout in your cellforRowAtIndexPath to tell the view to update its layout after you ahve set the text.