ScrollRectToVisible用于显示匹配的搜索字符串以滚动到UITextView的中间视图

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

我有一个用于显示详细文本的UiTextView。有时文本可以足够长以滚动它。有时文本可以足够短,以便它适合UITextView的框架。

我还实现了一个搜索功能,可以用来搜索更长的文本字符串。该函数将字体颜色属性添加到与搜索输入字符串匹配的文本中。该函数为每个匹配的搜索字符串输入收集NSRange值的数组。我正在使用正则表达式匹配搜索字符串并返回每个匹配的NSRange值数组。

我目前正在开发一个功能,可以将用户设置为匹配搜索字符串的UITextView位置。

我稍后会提供一个按钮,用户可以单击该按钮循环切换匹配项。

到目前为止,一切都运作良好。见下面的代码。 detailText是UITextView:

    // rangeOfSearchText uses a regex to return the range of the match. For text purposes, the function returns the first index only. 

   let rangeOfMatch = rangeOfSearchText(searchString: self.searchText!, UIText: self.detailText.text)

   let glyRange =  self.detailText.layoutManager.glyphRange(forCharacterRange: rangeOfMatch, actualCharacterRange:nil)

   let rect =  self.detailText.layoutManager.lineFragmentRect(forGlyphAt: NSMaxRange(glyRange), effectiveRange: nil)
   self.detailText.scrollRectToVisible(rect, animated: true)

虽然代码运行良好,但匹配的文本显示在生成的UITextView框架的底部。我希望匹配的文本出现在视图的中间。我尝试了以下有用的代码:

self.detailText.contentOffset.y = 200      

仅当匹配的文本范围位于较大的多行字符串的中间时,contentOffset才能按预期工作。如果匹配的文本范围位于字符串的开头,则实现contentOffset会将用户滚过匹配的文本200.基本上,匹配的文本滚动出视图。那不好。如果匹配的文本位于多行文本的末尾,则contentOffset会添加更多空格以将匹配的文本放置在视图的中间。这两种结果都不合适。我可以和后者一起生活,但前者并不好,因为它会将第一个匹配的文本滚动到视图之外。

我在堆栈溢出上搜索了类似的问题,但找不到它。如果确实存在,请指出它。如果没有,欢迎提出任何建议。

swift uitextview scrollrect
1个回答
0
投票

这似乎有效:

if rect.minY >= detailText.frame.height/2 {

self.detailText.scrollRectToVisible(rect.offsetBy(dx: 0.0, dy: detailText.frame.height/2), animated: true)

}

© www.soinside.com 2019 - 2024. All rights reserved.