Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center text vertically in a UITextView

I want to center the text vertically inside a big UITextView that fills the whole screen - so that when there's little of text, say a couple of words, it is centered by height. It's not a question about centering the text (a property that can be found in IB) but about putting the text vertically right in the middle of UITextView if the text is short, so there are no blank areas in the UITextView. Can this be done? Thanks in advance!

like image 632
Sergey Grischyov Avatar asked Sep 25 '12 21:09

Sergey Grischyov


People also ask

How do I center text vertically in a div?

To center both vertically and horizontally, use padding and text-align: center : I am vertically and horizontally centered.

How do I center text vertically in line-height?

Use line-height for vertical centering with a fixed height To vertically center a single line of text or an icon within its container, we can use the line-height property. This property controls the height of a line in a run of text and adds an equal amount of space above and below the line-box of inline elements.

How do I center text vertically in HTML?

For vertical alignment, set the parent element's width / height to 100% and add display: table . Then for the child element, change the display to table-cell and add vertical-align: middle . For horizontal centering, you could either add text-align: center to center the text and any other inline children elements.


1 Answers

First add an observer for the contentSize key value of the UITextView when the view is loaded:

- (void) viewDidLoad {      [textField addObserver:self forKeyPath:@"contentSize" options:(NSKeyValueObservingOptionNew) context:NULL];      [super viewDidLoad]; } 

Then add this method to adjust the contentOffset every time the contentSize value changes:

-(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}; } 
like image 114
CSolanaM Avatar answered Sep 26 '22 22:09

CSolanaM