[英]Measuring the height of lines in UITextView
我正在嘗試測量線條的高度,以將覆蓋層放置在UITextView
特定文本上。 具體來說,我所說的行是用\\n
分隔的文本。 因此,一條線實際上可以跨越多條線,這就是我要衡量的。 我嘗試了幾種不同的方法,但是,我似乎無法正確計算高度。 我當前方法的另一個缺點是必須全部在主同步線程上計算,這不理想,因為我需要進行大量計算。
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... :(
示例打印
應該是1行
30.0 18.625
應該是3行
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.