4
-(void)observeValueForKeyPath:(NSString *)keyPath   ofObject:(id)object   change:(NSDictionary *)change   context:(void *)context 
{
    NSLog(@"Hello");
    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};
}

I am calling it like this in Viewdidload

[myTextView1 addObserver:self forKeyPath:@"contentSize" options:(NSKeyValueObservingOptionNew) context:NULL];
Jitendra
  • 5,055
  • 2
  • 22
  • 42
Ahsan
  • 45
  • 1
  • 1
  • 4
  • 1
    Is this vertical alignment? Is there any reason you're using a UITextView over a UILabel? The label will do this for you for free. – SomeGuy Oct 07 '13 at 07:40
  • http://stackoverflow.com/questions/17024375/uitextview-alligining-text-vertically-center?rq=1 – peko Oct 07 '13 at 07:46

3 Answers3

13
textView.textAlignment = NSTextAlignmentCenter;
Raphael Royer-Rivard
  • 2,252
  • 1
  • 30
  • 53
user1673099
  • 3,293
  • 7
  • 26
  • 57
2

try this on iOS7:

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
    {
UITextView *tv = object;

CGFloat height = [tv bounds].size.height;
CGFloat contentheight;

if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7")) {
    contentheight = [tv sizeThatFits:CGSizeMake(tv.frame.size.width, FLT_MAX)].height;
    NSLog(@"iOS7; %f %f", height, contentheight);
}else{
    contentheight = [tv contentSize].height;
    NSLog(@"iOS6; %f %f", height, contentheight);
}

CGFloat topCorrect = height - contentheight;
topCorrect = (topCorrect <0.0 ? 0.0 : topCorrect);
tv.contentOffset = (CGPoint){.x = 0, .y = -topCorrect};
}

to be defined:

#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
Max B.
  • 881
  • 10
  • 21
  • 2
    This works great except for when the content fits on one line. then it aligns it with the bottom. If you add, ` CGFloat topCorrect = (height - contentheight * [tv zoomScale])/2.0;`, it works perfectly. – barndog Dec 04 '13 at 20:33
0

For swift:

        itemTextView.addObserver(self, forKeyPath:"contentSize", options: NSKeyValueObservingOptions.New, context: nil)

and

    override func observeValueForKeyPath(keyPath: String!, ofObject object: AnyObject!, change: [NSObject : AnyObject]!, context: UnsafeMutablePointer<Void>) {
    var tv : UITextView = object as UITextView;
    var height = tv.bounds.size.height;
    var contentheight = tv.sizeThatFits(CGSizeMake(tv.frame.size.width,1000)).height


    var topCorrect : CGFloat = height - contentheight;
    if(topCorrect < 0) {
        topCorrect = 0
    }
    tv.contentOffset = CGPointMake(0, -topCorrect/2)

}
Roman Barzyczak
  • 3,785
  • 1
  • 30
  • 44