如何使用 TextKit 2 获取 UITextView 的行数?

问题描述 投票:0回答:1

自 iOS 16 起,TextKit 2 已将 TextKit 1 替换为

UITextView
,这意味着
layoutManager
已过时,而
textLayoutManager
已入。但是,旧版本中的许多属性不在新版本中。如何使用 TextKit 2 计算
UITextView
中的行数?下面是 TextKit 1 的实现。

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)
        }
    }
}
ios swift uitextview
1个回答
0
投票

您可以使用

enumerateTextLayoutFragments
得到“真实”的行数,除以 ' '.

var count = 0
textView.textLayoutManager?.enumerateTextLayoutFragments(from: textView.textLayoutManager?.documentRange.location,
                                                         options: [.ensuresLayout, .ensuresExtraLineFragment],
                                                         using: { _ in
    count += 1
    return true // keep going
})
© www.soinside.com 2019 - 2024. All rights reserved.