让UITextView和UITextField同样拥有垂直居中的属性,建议单独一个类继承自UITextView
只需要初始化UITextView之后用KVO监听 “contentSize” 属性即可:

1
[textView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:NULL];
1
2
3
4
5
6
7
8
9
10
11
12
- (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};
}