ios - 将 UITextView 中的文本垂直和水平居中

标签 ios cocoa-touch uitextview

<分区>

我有一个包含一个单元格的分组 TableView 。在此单元格中,我将 UITextView 放入 cellForRowAtIndexPath: 中,我立即将其设为第一响应者。

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

如何让文本居中?

最佳答案

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

添加观察者如下:

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

按如下方式处理观察者操作:

-(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 并转到库并在该库中将 Alignment 设置为居中。

享受吧。 :)

关于ios - 将 UITextView 中的文本垂直和水平居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22013768/

相关文章:

ios - 使用 UILabel 文本掩码显示 UIView

ios - 如何使用3D Touch实现这样的分享?

ios - Objective C - NSArray的indexOfObject : not work

iOS Facebook 插屏广告

ios - 根据 iOS 6 通讯录使用文档,第 22 条规则

ios - 如何为 UITextView 中的特定单词设置样式?

iphone - 我是否想对 UI 变量使用除 "retain"和 "nonatomic"之外的任何 @property 属性?

iphone - 在 iOS8 中使用 UISearchBar 启用取消按钮

ios - 将 TextView 滚动到顶部

ios - 在 Swift 的 UITextView 中添加占位符文本?