Search code examples
objective-calignmentuitextview

UITextView Alignment like UILabel


Is there any way to change start-typing point of UITextview like UILabel?

I would like to type fonts starting point from the center on UITextView rather than default point from the upper left.

Anybody help me out kindly?

Cheers,

enter image description here


Solution

  • 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.