首页 > 解决方案 > 带有 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

那么有什么方法可以防止我的用户界面滞后?

标签: iosswiftiphonexcode

解决方案


推荐阅读