Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center the text in a UITextView, vertically and horizontally [duplicate]

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?

like image 367
user3083408 Avatar asked Feb 25 '14 12:02

user3083408


1 Answers

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. :)

like image 67
Vinay Jain Avatar answered Oct 03 '22 05:10

Vinay Jain