[英]Scroll UITextView to specific text
i have a uitextview with large texts and above i have a search field. 我有一个大文本和上面的uitextview我有一个搜索字段。 Anything searched, i would love the uitextview to scroll to that specific text and hightlight.
搜索到的任何内容,我都希望uitextview能够滚动到特定的文本和高光。 And i need to make sure that the uitextview scrolls in such a way that the searched text stays in the first line
我需要确保uitextview以一种搜索文本保留在第一行的方式滚动
I populated the textview with attributed text with some attributes. 我使用带有某些属性的属性文本填充textview。 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.
我尝试的是在目标文本之前获取文本并尝试获取它的大小,添加我在开头的textview文本中添加的确切属性。
made a CGPoint using that height and set the contentOffset of the uitextview. 使用该高度制作CGPoint并设置uitextview的contentOffset。 But the textview scrolled no where near the target text.
但是textview在目标文本附近没有滚动。 Maybe my approach is wrong as i dont have the width of the textview when setting attributes
也许我的方法是错误的,因为我在设置属性时没有textview的宽度
My code is : 我的代码是:
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)
}
}
}
}
Your approach is much more complicated than it needs to be. 你的方法比它需要的要复杂得多。 Use the
scrollRangeToVisible
method of UITextView
. 使用
UITextView
的scrollRangeToVisible
方法。
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)
}
}
Note the following: 请注意以下事项:
localizedStandardRange
when searching if you want to ignore diacritics and case, and you want other locale specific search features. localizedStandardRange
是否要忽略变音符号和大小写,并且您需要其他特定于语言环境的搜索功能。 selectedRange
if you want the matching text selected. selectedRange
如果你想选择匹配的文本。 If you want to get the selected range at the top, try something like this instead of calling scrollRangeToVisible
: 如果你想在顶部获得所选范围,尝试这样的事情而不是调用
scrollRangeToVisible
:
let rect = ayatTextView.layoutManager.boundingRect(forGlyphRange: viewRange, in: ayatTextView.textContainer)
ayatTextView.contentOffset = CGPoint(x: 0, y: rect.origin.y)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.