[英]Measuring the height of lines in UITextView
I am trying to measure the height of lines to place an overlay over specific text in a UITextView
. 我正在尝试测量线条的高度,以将覆盖层放置在
UITextView
特定文本上。 Specifically what I mean by lines is text delimitated with \\n
. 具体来说,我所说的行是用
\\n
分隔的文本。 So one line can actually span multiple lines and that is what I am trying to measure. 因此,一条线实际上可以跨越多条线,这就是我要衡量的。 I have tried a few different approaches, however, I can't seem to calculate the height correctly.
我尝试了几种不同的方法,但是,我似乎无法正确计算高度。 Another weakness with my current approaches is it has to be all calculated on the main synchronous thread which is less than ideal because I have a lot calculations to do.
我当前方法的另一个缺点是必须全部在主同步线程上计算,这不理想,因为我需要进行大量计算。
EXAMPLE UI APPROACH UI方法示例
measurement.font = UIFont(name: "Menlo", size: 16)
measurement.frame = CGRect(x: 0, y: 0, width: 10000, height: 50)
func heightForString(line: String) -> CGFloat {
var height : CGFloat = 0
measurement.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: 10000)
measurement.sizeToFit()
height = measurement.frame.height
print(height, lineHeight)
measurement.frame = CGRect(x: 0, y: 0, width: 10000, height: 50)
return height
}
// Comparing the returned height to measurement.font?.lineHeight and padding shows the results make little sense... :(
EXAMPLE PRINT 示例打印
Should be 1 line 应该是1行
30.0 18.625
30.0 18.625
Should be 3 lines 应该是3行
43.6666666666667 18.625
43.6666666666667 18.625
func heightForString(line: String) -> CGFloat {
let textView = UITextView()
let maxwidth = UIScreen.main.bounds.width
textView.frame = CGRect(x:0,y: 0,width: maxwidth,height: CGFloat(MAXFLOAT))
textView.textContainerInset = UIEdgeInsets.zero
textView.textContainer.lineFragmentPadding = 0
textView.font = UIFont(name: "Menlo", size: 16)
textView.text = line
textView.isScrollEnabled = false
textView.sizeToFit()
return textView.frame.size.height
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.