ios - 带有 NSAttributedString 的 UITextView 是滞后的
问题描述
我还是 swift 的新手,所以有一个我无法解决的问题。我正在做的是使用搜索器搜索某些关键字并突出显示它们(但焦点突出显示的颜色不同),它可以正常工作,但是当我的 UITextView 中的单词增加时(现在我的单词大约是 500 个字符),它变得如此滞后,这是我为突出显示关键字而实现的代码:
let attributed = NSMutableAttributedString(string: baseString! , attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 17.0)])
do {
let regex = try NSRegularExpression(pattern: lowercasekeyword!, options: NSRegularExpression.Options.caseInsensitive)
let matches = regex.matches(in: baselowercase!, options: [], range: NSMakeRange(0, baselowercase!.count))
if matches.count != 0{
search_view.isHidden = false
checkingResult = matches
keywordNext_btn?.isEnabled = true
keywordPrev_btn?.isEnabled = true
for match in matches.indices {
if match == 0{
attributed.addAttribute(NSAttributedString.Key.backgroundColor, value: UIColor.systemYellow, range: matches[0].range)
label.text = "1 of \(matches.count)"
if let range = smallTextview.textRangeFromNSRange(range: matches[0].range){
smallTextview.selectedTextRange = range
}
smallTextview.scrollRangeToVisible(smallTextview.selectedRange)
}else{
attributed.addAttribute(NSAttributedString.Key.backgroundColor, value: UIColor.lightGray, range: matches[match].range)
}
}
smallTextview.attributedText = attributed
还有一个我写的另一个函数,这个函数的用法是把我的关键字的高亮颜色改成下一个,比如关注下一个关键字:
let attributed = NSMutableAttributedString(string: smallTextview.text! , attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 17.0)])
index += 1
if index < checkingResult.count{
for match in checkingResult.indices{
if index == match{
attributed.addAttribute(NSAttributedString.Key.backgroundColor, value: UIColor.systemYellow, range: checkingResult[index].range)
if let range = smallTextview.textRangeFromNSRange(range: checkingResult[index].range){
smallTextview.selectedTextRange = range
}
smallTextview.scrollRangeToVisible(smallTextview.selectedRange)
label.text = "\(index+1) of \(checkingResult.count)"
}else{
attributed.addAttribute(NSAttributedString.Key.backgroundColor, value: UIColor.lightGray, range: checkingResult[match].range)
}
smallTextview.attributedText = attributed
我的 UI 看起来像这样: UI
那么有什么方法可以防止我的用户界面滞后?
解决方案
推荐阅读
- python - 在笔记本以外的其他上下文中嵌入 Jupyter 小部件时出错
- openshift - 无法使用 CLI 登录到 openshift
- excel - 私有函数跳过 For 循环
- javascript - 具有动态背景的 div 的最大高度和最大宽度?
- azure - Sharepoint 在线“不支持的仅应用程序令牌。”
- c++ - CodeLite 立即关闭终端
- flutter - Flutter:长文本链接,如隐私政策和服务条款
- mysql - 使用多个连接构建复杂的 MySQL 查询
- ssrs-2012 - 当项目编号发生变化时插入显示总数的空行
- glsl - 在顶点着色器中应用 Y 旋转时纹理坐标移动