目前,我有一个UITextView
(禁用滚动-UITextView inside UIScrollView with AutoLayout)
在一个UIScrollView
里面。
我们希望通过编程突出显示选定的文本。这就是我们所做的。
@IBAction func click(_ sender: Any) {
let attributedText = textView.attributedText!
let attributedString: NSMutableAttributedString = NSMutableAttributedString(attributedString: attributedText)
let range = NSRange(location: 0, length: attributedString.length)
attributedString.removeAttribute(NSAttributedString.Key.backgroundColor, range: range)
let searchedString = "Can you highlight and scroll?"
do {
let regex = try NSRegularExpression(
pattern: NSRegularExpression.escapedPattern(for: searchedString),
options: .caseInsensitive
)
let targetedString = attributedString.string
for match in regex.matches(in: targetedString, options: .withTransparentBounds, range: range) {
print(">>>> found the 1st match")
attributedString.addAttribute(NSAttributedString.Key.backgroundColor, value: UIColor.yellow, range: match.range)
break
}
} catch {
print("\(error)")
}
textView.attributedText = attributedString
}
其工作原理如以下视频所示。
除了手动滚动,我们还喜欢通过编程方式执行滚动,以使突出显示的文本可见。
请注意,执行以下代码将无法实现我们想要的效果
textView.scrollRangeToVisible(match.range)
- 这是因为在
UITextView
中禁用了滚动 *
我想知道,什么是一个适当的方式,我执行突出显示和滚动UITextView内的UIScrollView?
演示:https://github.com/yccheok/programming-issue/tree/main/highlight-and-scroll/demo
1条答案
按热度按时间toe950271#
你可以这样做,在textView layoutManager上使用boundingRect(forGlyphRange:in:)来获取特定范围的矩形,然后使用scrollView滚动到特定的矩形。
抱歉gif太小,无法放大:D