在UITextView中垂直居中对齐文本 [英] Aligning text vertically center in UITextView

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

问题描述

我正在将一些属性文本设置为textview,并给出一行.我正在尝试将基线对齐方式设置为垂直居中,但无法进行设置.如何在textview中将文本设置为垂直居中.

I am setting some attributed text to textview, and giving line. I am trying to set baseline alignment vertically center but unable to set that. How can I set the text vertically center in textview.

推荐答案

当视图出现/消失时,首先添加/删除UITextViewcontentSize键值的观察者:

First add/remove an observer for the contentSize key value of the UITextView when the view is appeared/disappeared:

override func viewWillAppear(animated: Bool) {
  super.viewWillAppear(animated)
  textView.addObserver(self, forKeyPath: "contentSize", options: NSKeyValueObservingOptions.New, context: nil)
}

override func viewWillDisappear(animated: Bool) {
  super.viewWillDisappear(animated)
  textView.removeObserver(self, forKeyPath: "contentSize")
}

Apple更改了内容偏移量和插图的工作方式,现在需要对这种经过稍微修改的解决方案进行设置,以将内容插图的顶部设置为顶部,而不是偏移量.

Apple has changed how content offsets and insets work this slightly modified solution is now required to set the top on the content inset instead of the offset.

/// Force the text in a UITextView to always center itself.
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
    let textView = object as! UITextView
    var topCorrect = (textView.bounds.size.height - textView.contentSize.height * textView.zoomScale) / 2
    topCorrect = topCorrect < 0.0 ? 0.0 : topCorrect;
    textView.contentInset.top = topCorrect
}

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

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