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

查看:25
本文介绍了如何垂直对齐 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.

提前致谢.

推荐答案

将您的 Text View 链接到您的 View Controller 并根据需要为其命名(例如 textView).

Link your Text View to your View Controller and name it as you want (let's say textView).

viewDidLayoutSubviews 函数中放置这一行:

In viewDidLayoutSubviews function put this line:

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

要在 Swift 2.0 中使用此函数,只需将 CGFloat.greatestFiniteMagnitude 更改为 CGFloat.max

To use this function in Swift 2.0 just change CGFloat.greatestFiniteMagnitude to CGFloat.max

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

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