如何在文本中查找指定单词并修改其颜色同时保留原有样式
问题原因
你当前的代码是用纯文本exampleTextView.text!创建了全新的NSMutableAttributedString,这个新字符串没有继承exampleTextView原本的任何文本属性(比如字体、默认文字颜色、字号等),所以当你把它赋值给attributedText时,原有样式就被覆盖成默认值了。
解决方案
正确的做法是基于控件现有的属性文本(或者把当前控件的默认样式先应用到整个文本上)来创建可变属性字符串,再修改目标单词的颜色:
// 高亮指定单词颜色 let color1 = UIColor.red let textToFind = newWordQuiz // 1. 获取或创建包含原有样式的可变属性字符串 var attrsString: NSMutableAttributedString if let existingAttrText = exampleTextView.attributedText { attrsString = NSMutableAttributedString(attributedString: existingAttrText) } else { // 如果原本没有设置attributedText,就用当前控件的样式创建属性字符串 let baseAttributes: [NSAttributedString.Key: Any] = [ .font: exampleTextView.font ?? UIFont.systemFont(ofSize: 17), .foregroundColor: exampleTextView.textColor ?? UIColor.black ] attrsString = NSMutableAttributedString(string: exampleTextView.text ?? "", attributes: baseAttributes) } // 2. 搜索并修改目标单词的颜色 let range = (attrsString.string as NSString).range(of: textToFind, options: .caseInsensitive) if range.length > 0 { attrsString.addAttribute(.foregroundColor, value: color1, range: range) } // 3. 赋值回控件 exampleTextView.attributedText = attrsString
额外说明
- 如果你的
exampleTextView原本就通过代码或Storyboard设置了字体、颜色等样式,上面的代码会完整保留这些样式,只修改目标单词的颜色。 - 若要匹配所有出现的目标单词(不止第一个),可以循环搜索直到找不到为止:
var searchRange = NSRange(location: 0, length: attrsString.string.count) while let foundRange = (attrsString.string as NSString).range(of: textToFind, options: .caseInsensitive, range: searchRange), foundRange.length > 0 { attrsString.addAttribute(.foregroundColor, value: color1, range: foundRange) // 更新搜索范围,避免重复匹配 searchRange = NSRange(location: foundRange.location + foundRange.length, length: attrsString.string.count - (foundRange.location + foundRange.length)) }
内容的提问来源于stack exchange,提问作者Dude1313
相关产品推荐
相关产品推荐

