I have a grouped table view with one cell. In this cell I'm putting a UITextView
in cellForRowAtIndexPath:
, and I instantly make this first Responder.
My problem is: When I start typing, the text is left-justified, not centered horizontally and vertically as I want. This is on iOS 7.
How can I center the text?
I resolve this issue by observing the contentsize of UITextView, when there is any change in the contentSize, update the contentOffset.
Add observer as follows:
[textview addObserver:self forKeyPath:@"contentSize" options:(NSKeyValueObservingOptionNew) context:NULL];
Handle the observer action as follows:
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
UITextView *txtview = object;
CGFloat topoffset = ([txtview bounds].size.height - [txtview contentSize].height * [txtview zoomScale])/2.0;
topoffset = ( topoffset < 0.0 ? 0.0 : topoffset );
txtview.contentOffset = (CGPoint){.x = 0, .y = -topoffset};
}
To make the textview text horizontally center, select the textview from .xib class and go to the library and in that set Alignment as center.
Enjoy. :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With