将文本居中放置在UITextView中,垂直和水平 [英] Center the text in a UITextView, vertically and horizontally

查看:1383
本文介绍了将文本居中放置在UITextView中,垂直和水平的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个单元格的分组表视图。在这个单元格中,我在 cellForRowAtIndexPath:中放置一个 UITextView ,我立即使第一个响应者。

I have a grouped table view with one cell. In this cell I'm putting a UITextView in cellForRowAtIndexPath:, and I instantly make this first Responder.

我的问题是:当我开始输入时,文本是左对齐的,不是水平和垂直居中我想要的。

My problem is: When I start typing, the text is left-justified, not centered horizontally and vertically as I want. This is on iOS 7.

推荐答案

我通过观察UITextView的contentsize来解决这个问题,当contentSize有任何变化时,更新contentOffset。

I resolve this issue by observing the contentsize of UITextView, when there is any change in the contentSize, update the contentOffset.

添加观察者如下:

[textview addObserver:self forKeyPath:@"contentSize" options:(NSKeyValueObservingOptionNew) context:NULL];

处理观察者操作,如下所示:

Handle the observer action as follows:

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
     UITextView *txtview = object;
     CGFloat topoffset = ([txtview bounds].size.height - [txtview contentSize].height * [txtview zoomScale])/2.0;
     topoffset = ( topoffset < 0.0 ? 0.0 : topoffset );
     txtview.contentOffset = (CGPoint){.x = 0, .y = -topoffset};
}

要使textview文本水平居中,从.xib类中选择textview,去图书馆,在那个集合对齐作为中心。

To make the textview text horizontally center, select the textview from .xib class and go to the library and in that set Alignment as center.

享受。 :)

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

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