Wednesday, 1 October 2014

Set Textview Text in Center Vertically and Horizontally


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.

But it is not easy to set is in centre for both vertically and Horizontally. 
but we can do it by observing the contentsize of UITextView, when there is any change in the contentSize, update the contentOffset.

Add observer as follows in viewDidLoad or viewWillAppear

[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};
}

Remove observer in viewDidUnLoad or viewWillDisappear depends on where you add

[textview removeObserver:self forKeyPath:@"contentSize" context:NULL];


Thanks & Regards
Angel AppTech

No comments:

Post a Comment

Note: only a member of this blog may post a comment.