When 2 or more lines are added to my UiTextView
it looks good but when the user enters just one line the text stays in the middle of the UiTextView
. How can I force it to stay on the top left side of the UiTextView
?
Asked
Active
Viewed 1,024 times
1

Segev
- 19,035
- 12
- 80
- 152
-
Check this blog [iOS: Vertical aligning text in a UITextView](http://imagineric.ericd.net/2011/03/10/ios-vertical-aligning-text-in-a-uitextview/) or rather just set `contentOffset` to an appropriate value(zero or so). – iDev Jan 18 '13 at 22:32
-
have you seen this http://stackoverflow.com/questions/3760924/set-line-height-in-uitextview – Rachel Gallen Jan 18 '13 at 22:35
2 Answers
1
You can check this blog (iOS: Vertical aligning text in a UITextView) which explains how to do center and bottom vertical alignment. Use similar logic and set contentOffset y param as zero in your case to make it top aligned.
This is the code from the blog,
- (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};
}

iDev
- 23,310
- 7
- 60
- 85
-
Thanks for your help but I just found a much simpler solution. The next code will move just the text: `[textView setContentInset:UIEdgeInsetsMake(5, 0, 5,0)]` – Segev Jan 18 '13 at 22:50
-
But that is setting `contentInset` and it will set even if number of lines are more than 1 right? I think I misread your question then. – iDev Jan 18 '13 at 22:52
-
It will always force the text to stay in the upper right corner of the UITextView. That was the case when 2 lines were in but with one line the text was centered for some reason. `ContentInset` fixes that issue. – Segev Jan 18 '13 at 23:11
1
I just found a much simpler solution. The next code will move just the text: [textView setContentInset:UIEdgeInsetsMake(5, 0, 5,0)]

Segev
- 19,035
- 12
- 80
- 152