我正在尝试滚动到位于UITextView的attributedText中的特定子字符串。滚动完成后,我希望子字符串位于可见textview文本的顶部。但是,当textView.selectedRange位于子字符串范围之下时,我只能将子字符串转到顶部。我怎样才能使子串总是出现在顶部,无论以前滚动范围在哪里?
这是我目前的代码
let text = // a long NSAttributedString
let substring = "put me at the top!"
textView.attributedText = text
func scrollToSubstring() {
let str = text.string as NSString
let range = str.rangeOfString(substring, options: .RegularExpressionSearch, range: NSMakeRange(0, str.length), locale: nil)
textView.scrollRangeToVisible(range)
// HOW CAN I MAKE IT SO range ALWAYS APPEARS AT THE TOP?
}
答案 0 :(得分:4)
UITextView
是UIScrollView
子类,因此如果您可以在滚动视图的坐标中找到子字符串的位置(可以使用TextKit
),那么您可以设置contentOffset
因此。这对我有用:
func scrollSubstringToTop() {
let str = text.string as NSString
let substringRange = str.rangeOfString(substring)
let glyphRange = textView.layoutManager.glyphRangeForCharacterRange(substringRange, actualCharacterRange: nil)
let rect = textView.layoutManager.boundingRectForGlyphRange(glyphRange, inTextContainer: textView.textContainer)
let topTextInset = textView.textContainerInset.top
let contentOffset = CGPoint(x: 0, y: topTextInset + rect.origin.y)
textView.setContentOffset(contentOffset, animated: true)
}