How to vertically center a UITextView
Note: I’ve moved all future technical/programming posts out of this blog and over to objectivesea.tumblr.com. Follow that one if you’re going to follow me for technical junk.
This took me ages to figure out how to vertically center the text in a UITextView. There really ought to be a property to set, but there isn’t so… this is pretty easy.
In -(void)viewDidLoad, add this to observe the contentSize key value:
[textView addObserver:self forKeyPath:@"contentSize" options:(NSKeyValueObservingOptionNew) context:NULL];
Then add this method, which adjusts the contentOffset every time the contentSize value changes.
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
UITextView *tv = object;
CGFloat topCorrect = ([tv bounds].size.height - [tv contentSize].height * [tv zoomScale]) / 2.0;
topCorrect = ( topCorrect < 0.0 ? 0.0 : topCorrect );
tv.contentOffset = (CGPoint){.x = 0, .y = -topCorrect};
}
Et voila!