Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITextView aligning text vertically center

Tags:

ios

uitextview

I want to align text vertically center in UItextView.

I am using following code

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}

;

Somehow this doesn't work in iOS 5 as the contentSize returned there is different what I get in iOS6.

Any Idea why contentSize of the same textView is different in iOS 5 and iOS 6?

like image 798
subhash Amale Avatar asked Jun 10 '13 12:06

subhash Amale


2 Answers

Add an observer for the contentSize key value of the UITextView when the view loaded :-

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

Adjust the contentOffset every time the contentSize value change :-

 -(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};
}

Hope it helps you...

You may take guide from

https://github.com/HansPinckaers/GrowingTextView

like image 156
Arpit Kulsreshtha Avatar answered Oct 13 '22 15:10

Arpit Kulsreshtha


try this on observeValueForKeyPath method 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)
like image 20
Max B. Avatar answered Oct 13 '22 14:10

Max B.