I wondered how to set the UITextView so that the text inside aligns to the bottom? Like, if you start typing, you will always type in the lowest row?
I don't believe there is a built-in way to vertically align the text in a UITextView
, but you should be able to use the contentOffset
property of the UITextView
class to accomplish this. See this blog post for more details:
http://imagineric.ericd.net/2011/03/10/ios-vertical-aligning-text-in-a-uitextview/
Update: since the above link appears to be dead, I used the Wayback Machine to retrieve an archived copy and have pasted the text of the article below.
The default and expected behavior of a UITextView (multi-line text) out of the box in iOS is to align the text top left in it’s container. That works well most of the time. However I recently had need to either center the text vertically within the control or have all the text align to the bottom of the control.
You can add an observer to the control and when it’s content size changes (text is set), fire a method. The method can then handle how the text is actually positioned in the control. If it doesn’t make sense to do the alignment, it will default to the normal behavior of the control (top vertical alignment).
Here we go:
- (void) viewDidLoad {
[textField addObserver:self forKeyPath:@"contentSize" options:(NSKeyValueObservingOptionNew) context:NULL];
[super viewDidLoad];
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
UITextView *tv = object;
//Center vertical alignment
//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};
//Bottom vertical alignment
CGFloat topCorrect = ([tv bounds].size.height - [tv contentSize].height);
topCorrect = (topCorrect <0.0 ? 0.0 : topCorrect);
tv.contentOffset = (CGPoint){.x = 0, .y = -topCorrect};
}
You can decide which you’d like to use, or flush the method out to take an argument for which type of vertical alignment you’d like to use. This works quite well and it would have been nice if the properties were built into the control to begin with.
If you can use it, enjoy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With