George H George H - 1 month ago 6
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: http://stackoverflow.com/a/38855122/4660602

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

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

EDIT:

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.

Thanks!

Answer

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.

Comments