Since iOS 16, TextKit 2 has replaced TextKit 1 for UITextView
which means layoutManager
is out and textLayoutManager
is in. However, a number of the properties from the old are not in the new. How can I calculate the number of lines in a UITextView
using TextKit 2? Below is the TextKit 1 implementation.
extension UITextView {
var numberOfLines: Int {
if #available(iOS 16.0, *) {
// TextKit 2
let layout = textLayoutManager // new layout manager
} else {
// TextKit 1
let layout = layoutManager // old layout manager
var lines = 0
var index = 0
var lineRange = NSRange()
while index < layout.numberOfGlyphs {
layout.lineFragmentRect(forGlyphAt: index, effectiveRange: &lineRange)
index = NSMaxRange(lineRange)
lines += 1
}
return max(1, lines)
}
}
}