如何计算 UITextView 相对于原点的第一个基线位置 [英] How to calculate UITextView first baseline position relatively to the origin

查看:28
本文介绍了如何计算 UITextView 相对于原点的第一个基线位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何计算 UITextView 第一个基线位置?

How can I calculate UITextView first baseline position?

我试过这样计算:

self.textView.font!.descender + self.textView.font!.leading

但是,我得到的值不正确.有什么想法、提示吗?

However, the value I'm getting is not correct. Any ideas, hints?

推荐答案

根据 zcui93 提供的文档,font.ascender 将为您提供字体内基线的偏移量.要在 UITextView 中获取字体的基线,您需要在 textContainerInset.top 中添加:

Based on the documentation zcui93 gives, font.ascender will give you the offset to the baseline within the font. To get the baseline of the font within the UITextView you need to add in textContainerInset.top:

extension UITextView {
    func firstBaseline() -> CGFloat {
        let font = self.font ?? UIFont.systemFontOfSize(UIFont.systemFontSize())
        return font.ascender + textContainerInset.top
    }
}

如果没有设置字体,这里有一些默认系统字体的假设,但我不确定更好的猜测是什么.

There's a little bit of assumption here in defaulting to the system font if no font is set, but I'm not sure what a better guess would be.

在 Playground 中运行以下代码将演示效果:

Running the following in the playground will demonstrate the effect:

class Container : UITextView {
    override func drawRect(rect: CGRect) {
        let context = UIGraphicsGetCurrentContext()
        CGContextSaveGState(context)

        let containerRect = UIEdgeInsetsInsetRect(bounds, textContainerInset)
        UIColor(red: 1, green: 0, blue: 0, alpha: 0.25).setFill()
        CGContextFillRect(context, containerRect)

        let baseline = firstBaseline()

        UIColor(red: 1, green: 0, blue: 0, alpha: 0.75).setStroke()
        CGContextSetLineWidth(context, 1)
        CGContextMoveToPoint(context, containerRect.origin.x, baseline)
        CGContextAddLineToPoint(context, containerRect.origin.x + containerRect.width, baseline)
        CGContextStrokePath(context)

        super.drawRect(rect)
    }
}

let textView = Container(frame: CGRect(x: 0, y: 0, width: 100, height: 30))
textView.font = UIFont.systemFontOfSize(UIFont.systemFontSize())
textView.text = "My Text"

结果:

这篇关于如何计算 UITextView 相对于原点的第一个基线位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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