UITextView垂直居中对齐文本

问题描述:

我想在 UItextView 中垂直居中对齐文字。

I want to align text vertically center in 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}

;

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

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

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

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

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

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

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

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...

您可以参考

https:// github。 com / HansPinckaers / GrowingTextView