我的应用程序中有一个 TextView ,允许用户在其中键入任何内容。我希望 TextView 在输入时检测到一些单词并改变它们的颜色。
例如,如果用户键入“我最喜欢的颜色是红色”,那么我希望单词“红色”获得文本颜色“红色”。但是,thus 应该在句子中输入 red 之后立即发生。我应该如何实现?
最佳答案
你需要三样东西:
在界面生成器中,您需要使用其中一种委托(delegate)方法。我认为“editingChanged”是这里最好的。使用“ctrl”从文本字段拖动到您的文档。
您需要一种方法来遍历文本字段中的字符串并检测单词。
componentsSeparatedByCharactersInSet
您需要一种方法来为句子中的一个词设置样式。
NSMutableAttributedString
也很有趣:how to separate a string without removing the delimiter
部分代码(扔在 Playground 上):
这将找到所有要更改的单词,但会删除分隔符。需要做更多工作才能完成代码。
var strSeperator : NSCharacterSet = NSCharacterSet(charactersInString: ",.:;?! ")
var strArray = str.componentsSeparatedByCharactersInSet(strSeperator)
var styledText = NSMutableAttributedString()
for i in 0..<strArray.count {
let currentWord = strArray[i]
var currentBoolFoundInControl : Bool = false
for iB in 0..<colorTheseStrings.count {
let controlWord = colorTheseStrings[iB]
if controlWord == currentWord {
currentBoolFoundInControl = true
// add to mutable attributed string in a color
}
}
var attrString1 = NSMutableAttributedString(string: "\(strArray[i]) ")
if currentBoolFoundInControl == true {
var range = (strArray[i] as NSString).rangeOfString(strArray[i])
if strArray[i] == "red" {
attrString1.addAttribute(NSForegroundColorAttributeName, value: UIColor(red: 0.5, green: 0.0, blue: 0.0, alpha: 1.0), range: range)
} else if strArray[i] == "blue" {
attrString1.addAttribute(NSForegroundColorAttributeName, value: UIColor(red: 0.0, green: 0.0, blue: 0.5, alpha: 1.0), range: range)
}
}
styledText.appendAttributedString(attrString1)
}
myTextField.attributedText = styledText
另一种方式:
我觉得这种方式是最稳健最酷最高效的。 代码可以稍微清理一下,可以使用更多的风格/风格。这对于“天蓝色”之类的东西确实有麻烦,因为它会首先找到“蓝色”并替换它。但我不得不留下一些改进的余地。 ;)
我情不自禁,所以我解决了最后一个问题。
再一次,我修复了,我的修复。现在更有效率并且实际上是正确的。
第一部分是 HighLighter 类,将其放在单独的文档中。
// text hightlighter
class SyntaxGroup {
var wordCollection : [String] = []
var type : String = ""
var color : UIColor = UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
init(wordCollection_I : [String], type_I : String, color_I: UIColor) {
wordCollection = wordCollection_I
type = type_I
color = color_I
}
}
class SyntaxDictionairy {
var collections : [SyntaxGroup] = []
}
class SyntaxRange {
var range : NSRange
var color : UIColor
init (color_I : UIColor, range_I : NSRange) {
color = color_I
range = range_I
}
}
class HighLighter {
var ranges : [SyntaxRange] = []
var baseString : NSMutableString = NSMutableString()
var highlightedString : NSMutableAttributedString = NSMutableAttributedString()
var syntaxDictionairy : SyntaxDictionairy
init (syntaxDictionairy_I : SyntaxDictionairy) {
syntaxDictionairy = syntaxDictionairy_I
}
func run(string : String?, completion: (finished: Bool) -> Void) {
ranges = [] // reset the ranges, else it crashes when you change a previous part of the text
highlightedString = NSMutableAttributedString() // make sure all strings start fresh
baseString = NSMutableString() // make sure all strings start fresh
// multi threading to prevent locking up the interface with large libraries.
let qualityOfServiceClass = QOS_CLASS_DEFAULT
let backgroundQueue = dispatch_get_global_queue(qualityOfServiceClass, 0)
dispatch_async(backgroundQueue) { () -> Void in
if string != nil && string != "" {
self.highlightedString = NSMutableAttributedString(string: string!)
for i in 0..<self.syntaxDictionairy.collections.count {
for iB in 0..<self.syntaxDictionairy.collections[i].wordCollection.count {
let currentWordToCheck = self.syntaxDictionairy.collections[i].wordCollection[iB]
self.baseString = NSMutableString(string: string!)
while self.baseString.containsString(self.syntaxDictionairy.collections[i].wordCollection[iB]) {
let nsRange = (self.baseString as NSString).rangeOfString(currentWordToCheck)
let newSyntaxRange = SyntaxRange(color_I: self.syntaxDictionairy.collections[i].color, range_I: nsRange)
self.ranges.append(newSyntaxRange)
var replaceString = ""
for _ in 0..<nsRange.length {
replaceString += "§" // secret unallowed character
}
self.baseString.replaceCharactersInRange(nsRange, withString: replaceString)
}
}
}
for i in 0..<self.ranges.count {
self.highlightedString.addAttribute(NSForegroundColorAttributeName, value: self.ranges[i].color, range: self.ranges[i].range)
}
}
dispatch_sync(dispatch_get_main_queue()) { () -> Void in
completion(finished: true)
}
}
}
}
在 View Controller 中: 这是您将与 UITextfield 一起使用的代码。 首先创建一个荧光笔实例并设置你的单词字典和相应的颜色。然后在需要的时候启动run函数。
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var myTextfield: UITextField!
var syntaxHighLighter : HighLighter! // declare highlighter
override func viewDidLoad() {
super.viewDidLoad()
setUpHighLighter()
}
// this is just a little function to put the set up for the highlighter outside of viewDidLoad()
func setUpHighLighter() {
// build a dict of words to highlight
let redColor = UIColor(red: 0.5, green: 0.0, blue: 0.0, alpha: 1.0)
let blueColor = UIColor(red: 0.0, green: 0.0, blue: 0.5, alpha: 1.0)
let greenColor = UIColor(red: 0.0, green: 0.5, blue: 0.0, alpha: 1.0)
let redGroup = SyntaxGroup(wordCollection_I: ["red","bordeaux"], type_I: "Color", color_I: redColor)
let blueGroup = SyntaxGroup(wordCollection_I: ["coralblue","blue","skyblue","azur"], type_I: "Color", color_I: blueColor)
let greenGroup = SyntaxGroup(wordCollection_I: ["green"], type_I: "Color", color_I: greenColor)
let dictionairy : SyntaxDictionairy = SyntaxDictionairy()
dictionairy.collections.append(blueGroup)
dictionairy.collections.append(greenGroup)
dictionairy.collections.append(redGroup)
syntaxHighLighter = HighLighter(syntaxDictionairy_I: dictionairy)
}
// this is where the magic happens, place the code from inside the editingChanged inside your function that responds to text changes.
@IBAction func editingChanged(sender: UITextField) {
syntaxHighLighter.run(myTextfield.text) { (finished) -> Void in
self.myTextfield.attributedText = self.syntaxHighLighter.highlightedString
}
}
}
关于ios - 使 TextView 响应用户键入的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32356321/