如何在textView内垂直对齐文本? [英] How to align text inside textView vertically?

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

问题描述

我想使UITextView中的文本垂直对齐(因此它将位于文本的中间). 我怎样才能做到这一点? 我抬起头,找不到任何可以帮助我的答案.

I want to align vertically the text inside my UITextView (so it will be in the middle of it). How can i achieve that? I looked up and could not find any answer that could help me.

谢谢.

推荐答案

将您的textview链接到您的viewcontroller并根据需要命名(例如textView).

Link your textview to your viewcontroller and name it as you want (let's say textView).

viewDidLayoutSubviews函数中输入以下行:

textView.centerVertically()

然后在课程的最后一个大括号下放置此扩展名:

Then under the last curly bracket of your class put this extension:

  extension UITextView {

    func centerVertically() {
        let fittingSize = CGSize(width: bounds.width, height: CGFloat.greatestFiniteMagnitude)
        let size = sizeThatFits(fittingSize)
        let topOffset = (bounds.size.height - size.height * zoomScale) / 2
        let positiveTopOffset = max(1, topOffset)
        contentOffset.y = -positiveTopOffset
    }

}

要将此功能用于 swift2 ,只需将CGFloat.greatestFiniteMagnitude更改为CGFloat.max

To use this function for swift2 just change CGFloat.greatestFiniteMagnitude to CGFloat.max

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

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