当用户在 UITextView 中键入“@”符号时从列表中搜索数据

Search data from list when user type '@' Symbol in UITextView

当用户在 UITextView 中输入带有特定搜索关键字的“@”时,是否可以显示下拉列表。

例如:

键入“@ios”,所有包含单词 "ios" 的字符串从列表中过滤并显示在下拉列表中。

我想你正在寻找类似 this.This 的东西,只要用户按下 @ 键,就会调用委托

试试这个:-

func textView(_ textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
    if (textView.text.appending(text) == "@") {
        //trigger '@' operation
        if arrayObject.contains(value) {
            //Populate array and display tableview.
        }
    }
    else if (textView.text.appending(text) == "/") {
        //trigger / operation
    }
    //Same conditions go on
}

我通过不断检查用户输入的文本来实现这一点。

func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {

    // if user type any latter from @,space and new line then clear the search string
    if text == "@" || text == " " || text == "\n" {
        self.searchString = ""
    }
    // append the type string in text view text
    let resultString = textView.text.stringByAppendingString(text)
    // break the line with @ symbol and find the occurence
    let numberOfOccurrences = resultString.componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString: "@")).count - 1
    // store all words for checking
    let stringArray = resultString.componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString: "@")) ?? [String]()
    // checking if string array > 1 that means string contains @ symbol
    self.searchString = stringArray.count > 1 ? stringArray[numberOfOccurrences].containsString(" ") ? "" : stringArray[numberOfOccurrences] : ""
    if self.searchString.characters.count > 0 {
        self.getTopSearchFromLive(self.searchString)
    } else {
        self.tableView.hidden = true
    }
    return true
}