JKMania JKMania - 1 month ago 4x
iOS Question

How to align text horizontally & vertically in UITextView?

How to align text horizontally & vertically in UITextView?
I want align text in UITextView with horizontal alignment & vertical alignment.
Is there any custom way?
Please help me out.....

Gad Gad

As far as I know there is no built in method for vertical alignment of a UITextView. However, by updating the the contentOffset you can get vertically centered text:

[textView setTextAlignment:NSTextAlignmentCenter];

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [textView addObserver:self forKeyPath:@"contentSize" options:(NSKeyValueObservingOptionNew) context:NULL];

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [textView removeObserver:self forKeyPath:@"contentSize"];

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