I want to align vertically some text in UITextView.When I added text.It shows from top..But I need to show middle from top.Is it possible to achieve this.
Asked
Active
Viewed 9,593 times
4
-
Before Upvote this post try to solve this.Then i will agree this is waste one.Can you? – SURESH SANKE Jun 27 '12 at 11:01
-
Look at the UIBaselineAdjustment in the [Apple Docs](http://developer.apple.com/library/ios/#DOCUMENTATION/UIKit/Reference/NSString_UIKit_Additions/Reference/Reference.html#//apple_ref/doc/c_ref/UITextAlignment). – tarheel Jun 27 '12 at 10:34
-
when i wrote like txt_view_head.textAlignment=UIBaselineAdjustmentAlignCenters; it shows nothing – SURESH SANKE Jun 27 '12 at 10:42
-
I used that one UIBaseLineAdju... but no use – SURESH SANKE Jun 27 '12 at 12:09
-
The baseline adjust.. is for horizontal alignment i think.When i used it shows only horizontal alignment not vertical(from top) – SURESH SANKE Jun 27 '12 at 12:22
2 Answers
4
You can be able to use the contentOffset
property of the UITextView
class to accomplish this.
See this Blog. I hope it helps you.
-
I have the textview in IB.having height of 80. I was unable to proceed with the code .It is having confusion. – SURESH SANKE Jun 27 '12 at 11:07
-
2To clarify for anyone reading this: If you want to vertical align and you use the code from the link Maulik provides here, you have to *uncomment* the vertical align part and *comment out* the bottom align part. – Murdock Oct 20 '12 at 00:21
-
UITextView (and other UIKit classes) are not guaranteed to be KVO compliant. Relying on this could cause your code to break in future iOS versions. See this post by a member of the UIKit development team: http://stackoverflow.com/a/6051404/357641 – Greg Aug 28 '13 at 17:44
0
- (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};
}

n00bProgrammer
- 4,261
- 3
- 32
- 60

Naveed Rafi
- 2,503
- 5
- 32
- 40