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

时间:2015-09-02 14:46:00

标签: ios swift xcode6 uitextview

我的应用程序中有一个文本视图,允许用户在其中键入任何内容。我希望文本视图在键入时检测几个单词并更改其颜色。

例如,如果用户输入“我喜欢的颜色是红色”,那么我希望“红色”这个词让文字颜色为“红色”。但是因此应该在句子中输入红字后立即发生。我该如何实现呢?

5 个答案:

答案 0 :(得分:5)

你需要三件事:

  • 在界面构建器中,您需要使用其中一种委托方法。我认为“editingChanged”在这里是最好的。使用“ctrl”从文本字段拖动到文档。

  • 您需要一种方法来检查文本字段中的字符串并检测单词。

    componentsSeparatedByCharactersInSet

  • 你需要一种方法来在一个句子中设置一个单词。

    NSMutableAttributedString

同样有趣:how to separate a string without removing the delimiter

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

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

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

另一种方式:

download it here

我认为这种方式最强大,最酷,最有效。 代码可以清理一下,可以使用更多的风格/风格。这确实有“天蓝色”之类的问题,因为它会首先找到“蓝色”并替换它。但我不得不留下一些改进空间。 ;)

我无法自拔,所以我修复了最后一期。

再一次,我修复了,我的修复。现在更高效,更实际。

第一部分是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一起使用的代码。 首先创建荧光笔的实例并设置单词和相应颜色的字典。然后在需要时启动运行功能。

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
        }
    }
}

答案 1 :(得分:3)

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)

}

答案 2 :(得分:1)

也许你可以实现Text View Delegate来检测用户何时完成输入,在条件中询问书面文字是否是你想要的,并且在肯定的情况下做某事(改变颜色)。 这里有一些文档https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITextViewDelegate_Protocol/ 你可以尝试实现这样的东西:

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)
     }
}

此代码只是一个架构。阅读文档并检查语法。希望它有所帮助!!

菲德

答案 3 :(得分:0)

您必须在UITextView委托方法

中使用attributedText
- (void)textViewDidChange:(UITextView *)textView

这将解决您的问题。

答案 4 :(得分:0)

我认为你应该做的就是这个(纠正我,如果我错了,因为我没有让Xcode在这台计算机上进行测试,但这应该有效)。如果那不起作用,做Fawad Masud并将其添加到视图中确实加载......

 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()

   }
}