UITextView垂直居中对齐文本

sub*_*ale 7 uitextview ios

我想将文本垂直居中对齐UItextView.

我正在使用以下代码

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}
Run Code Online (Sandbox Code Playgroud)

;

不知怎的,这在iOS 5中不起作用,因为返回的contentSize与我在iOS6中得到的不同.

任何想法为什么contentSize相同的textView在iOS 5和iOS 6中有所不同?

Arp*_*tha 20

加载视图时,为UITextView的contentSize键值添加一个观察者: -

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

每次contentSize值更改时调整contentOffset: -

 -(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};
}
Run Code Online (Sandbox Code Playgroud)

希望它能帮到你......

你可以从中获取指导

https://github.com/HansPinckaers/GrowingTextView


Max*_*llo 5

在iOS7上的observeValueForKeyPath方法上试试这个:

-(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};
}
Run Code Online (Sandbox Code Playgroud)

被定义为:

#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
Run Code Online (Sandbox Code Playgroud)