UITextView垂直居中对齐文本 [英] UITextView aligning text vertically center

查看:148
本文介绍了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

这篇关于UITextView垂直居中对齐文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆