iosswiftuitextviewuitextviewdelegate

UITextView searching for keywords in a database


I want to check if the user types specific phrases in a UITextView for a science app. I have this current code that creates a string of the last 20 characters then checks if that string contains a word in the arrayOfWords which gets performed on textViewDidChange:

var arrayOfWords = [“Gold", “Phosphorus”]

func textViewDidChange(_ textField: UITextView) {
    if let selectedRange = textView.selectedTextRange {
        let cursorPosition = textView.offset(from: textView.beginningOfDocument, to: selectedRange.start)
        let startRange = cursorPosition - 20
        let result = textView.text.substring(from: startRange, to: cursorPosition)

        checkIfContains(textViewString: result)
    }}

func checkIfContains(textViewString: String)  {
    if arrayOfWords.contains(where: textViewString.contains) {
        doAction()
    }
}

I know this is a very specific function so any ideas on how I could go about achieving this would be greatly appreciated.


Solution

  • Try to look at a regular expression (REGEX).

    In your case the regex should look like "([A-Za-z]\w+ [1-9]\.[1-9]*) " ( note the space at the end )

    Then in your textViewDidChange, as soon as the text matches the regex you can trigger your fetching method, and considering there is a space at the end it will only trigger when the user press space as you said.

    Here is a link to try your regex : https://regexr.com/

    And here is an example of using regex in swift : https://stackoverflow.com/a/27880748/5464805