在 UITextView 中垂直居中文本 [英] Center text vertically in a UITextView

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

问题描述

我想将文本垂直居中放置在一个大的 UITextView 中,填充整个屏幕 - 这样当文本很少时,说几句话,它是以高度为中心.这不是关于居中文本(可以在 IB 中找到的属性)的问题,而是关于将文本 垂直 放在 UITextView if 文本很短,所以UITextView 中没有空白区域.这能做到吗?提前致谢!

I want to center the text vertically inside a big UITextView that fills the whole screen - so that when there's little of text, say a couple of words, it is centered by height. It's not a question about centering the text (a property that can be found in IB) but about putting the text vertically right in the middle of UITextView if the text is short, so there are no blank areas in the UITextView. Can this be done? Thanks in advance!

推荐答案

先为UITextViewcontentSize键值添加一个观察者,当视图加载时:

First add an observer for the contentSize key value of the UITextView when the view is loaded:

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

然后在每次contentSize值改变时添加这个方法来调整contentOffset:

Then add this method to adjust the contentOffset every time the contentSize value changes:

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

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

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