使文本视图响应用户键入的文本

我在我的应用程序中允许用户键入任何内容的文本视图。 我想让文本视图在input时检测几个字,并更改它们的颜色。

例如 ,如果用户键入“我最喜欢的颜色是红色的”,那么我希望单词“红色”使文本颜色为“红色”。 但是,在句子中键入红色这个词之后应该立即发生。 我应该如何执行这个?

你需要三件事情:

  • 在界面生成器中,您需要使用其中一个委托方法。 我认为“editingChanged”是最好的。 用“ctrl”从文本框拖到你的文档。

  • 您需要从文本字段中检索string并检测单词。

    componentsSeparatedByCharactersInSet

  • 你需要一种方式来devise一个句子中的一个单词。

    NSMutableAttributedString

另外有趣的是: 如何在不删除分隔符的情况下分隔string

部分代码(扔在操场上):

这将find所有的单词改变,但删除分隔符。 需要更多的工作来完成代码。

 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 

另一种方式:

在这里下载

我认为这是最强劲,最酷,最有效的方式。 代码可以清理一下,可以使用更多的风格/风格。 这对于“azure色”这样的东西确实有问题,因为它会先find“蓝色”并将其replace。 但是我不得不留下一些改进的余地。 ;)

我不能自救,所以我解决了最后一个问题。

再次,我修好了,我的修理。 现在更高效,实际上是正确的。

第一部分是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) } } } } 

在ViewController中:这是你将用于UITextfield的代码。 首先创build一个荧光笔的实例,并build立你的字和相应的颜色的字典。 然后在需要时启动运行function。

 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 } } } 
 textField.addTarget(self, action: "textFieldDidChange:",forControlEvents: UIControlEvents.EditingChanged) func textFieldDidChange(textField: UITextField) { //your code var main_string = textField.text var string_to_color = "red" var range = (main_string as NSString).rangeOfString(string_to_color) var attributedString = NSMutableAttributedString(string:main_string) attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor() , range: range) } 

也许你可以实现文本视图委托来检测用户何时完成键入,如果写入的文本是你想要的,在有条件的情况下做一些事情(改变颜色)。 在这里你有一些文档https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITextViewDelegate_Protocol/你可以尝试执行这样的事情&#xFF1A;

 let text: UITextView? //this must be binded with the storyboard ui //MARK UITextViewDelegate func textViewDidChange(_ textView: UITextView){ if (textView.text == "bla"){ textView.colour == UIColour(Red) } } 

这段代码只是一个模式。 阅读文档并检查语法。 希望能帮助到你!!

菲德

您必须使用UITextView委托方法中的属性文字

 - (void)textViewDidChange:(UITextView *)textView 

这将解决你的问题。

我认为你应该做的是这个(纠正我,如果我错了,因为我没有Xcodetesting在这台计算机上,但这应该工作)。 如果这不起作用,福瓦德马苏德,并添加此查看加载…

  yourTextView.addTarget(self, action: "textViewDidChange:",forControlEvents: UIControlEvents.EditingChanged) 

 override func viewDidLoad() { super.viewDidLoad() yourTextView.delegate = self //Basically makes the function below applicable to this textview } func textViewDidChange(textView: UITextView) { //Every time text changes this code is run var textViewText = yourTextView.text as NSString! if textViewText.containsString("red") { textViewText.textColor = UIColor.redColor() } }