将 UITextView 滚动到特定文本 [英] Scroll UITextView to specific text
问题描述
我有一个带有大文本的uitextview,上面有一个搜索字段.搜索任何内容,我都希望 uitextview 滚动到该特定文本并突出显示.而且我需要确保 uitextview 以这样一种方式滚动,即搜索到的文本保留在第一行
i have a uitextview with large texts and above i have a search field. Anything searched, i would love the uitextview to scroll to that specific text and hightlight. And i need to make sure that the uitextview scrolls in such a way that the searched text stays in the first line
我用带有一些属性的属性文本填充了文本视图.我尝试的是在目标文本之前获取文本,并尝试获取它的大小,添加我在开始时在 textview 文本上添加的确切属性.
I populated the textview with attributed text with some attributes. What i tried is get the text before the target text and tried to get the size of it adding the exact attributes i added on textview text at the beginning.
使用该高度创建一个 CGPoint 并设置 uitextview 的 contentOffset.但是 textview 在目标文本附近没有滚动.也许我的方法是错误的,因为我在设置属性时没有 textview 的宽度
made a CGPoint using that height and set the contentOffset of the uitextview. But the textview scrolled no where near the target text. Maybe my approach is wrong as i dont have the width of the textview when setting attributes
我的代码是:
func goToBla() {
if let string = ayatTextView.text {
if let range = string.range(of: tazweedAyahas[8].text) {
let firstPart = string[string.startIndex..<range.lowerBound]
print("before \(tazweedAyahas[5].text) : ")
print(firstPart)
if let otherStr = firstPart as? NSString {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center
let size = otherStr.size(withAttributes: [NSAttributedStringKey.paragraphStyle: paragraphStyle,
NSAttributedStringKey.font: UIFont(name: "me_quran", size: 30)
])
let point = CGPoint(x: 0, y: size.height)
ayatTextView.setContentOffset(point, animated: true)
}
}
}
}
推荐答案
您的方法比它需要的要复杂得多.使用UITextView
的scrollRangeToVisible
方法.
Your approach is much more complicated than it needs to be. Use the scrollRangeToVisible
method of UITextView
.
func goToBla() {
if let string = ayatTextView.text, let range = string.localizedStandardRange(of: tazweedAyahas[8].text) {
let viewRange = NSRange(range, in: string)
ayatTextView.selectedRange = viewRange // optional
ayatTextView.scrollRangeToVisible(viewRange)
}
}
注意以下几点:
- 如果您想忽略变音符号和大小写,并且需要其他特定于区域设置的搜索功能,请在搜索时使用
localizedStandardRange
. - 如果您希望选择匹配的文本,请调用
selectedRange
.
如果您想在顶部获取所选范围,请尝试这样的操作,而不是调用 scrollRangeToVisible
:
If you want to get the selected range at the top, try something like this instead of calling scrollRangeToVisible
:
let rect = ayatTextView.layoutManager.boundingRect(forGlyphRange: viewRange, in: ayatTextView.textContainer)
ayatTextView.contentOffset = CGPoint(x: 0, y: rect.origin.y)
这篇关于将 UITextView 滚动到特定文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!