在UISearchBar中单击退格键时如何更新结果?

时间:2019-04-15 07:19:38

标签: ios swift uitableview uitextfield uisearchbar

我是Swift和Xcode的初学者。我有一个UITableview,其中包含项目列表和一个UISearchBar。我希望每次从UISearchBar的文本字段添加或删除字母时都对列表进行过滤。

输入字母时一切正常,但是使用我拥有的代码,当擦除某些字母时,无法获得列表来带回某些项目,直到文本字段为空且整个列表被称为。


func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        self.view.endEditing(true)
}

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        if searchBar.text?.count == 0 {
            loadListOfExercises()

            DispatchQueue.main.async {
                searchBar.resignFirstResponder()
            }
        }
        else {
            listOfExercises = listOfExercises?.filter("nameOfExercise CONTAINS[cd] %@", searchBar.text!).sorted(byKeyPath: "nameOfExercise", ascending: true)            
            self.listTableView.reloadData()
        }
    }

这是我用于loadListOfExercises()的代码

func loadListOfExercises() {

        listOfExercises = realm.objects(ExerciseInList.self)

        self.listTableView.reloadData()

    }

2 个答案:

答案 0 :(得分:0)

请参阅下面的代码来确定退格

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {        
    if searchBar.text?.count == 0 {
        loadListOfExercises()
        self.listTableView.reloadData()
        DispatchQueue.main.async {
            searchBar.resignFirstResponder()
        }
    }else {
        listOfExercises = listOfExercises?.filter("nameOfExercise CONTAINS[cd] %@", searchBar.text!).sorted(byKeyPath: "nameOfExercise", ascending: true)
        self.listTableView.reloadData()
    }

    if let char = searchText.cString(using: String.Encoding.utf8) {
        let isBackSpace = strcmp(char, "\\b")
        if (isBackSpace == -92) {
            print("Backspace was pressed")
            //Reload Your data here
        }
    }
}

答案 1 :(得分:0)

这里的错误是您在集合上调用filter方法并将其分配给同一集合,如下所示:

listOfExercises = listOfExercises?.filter("nameOfExercise CONTAINS[cd] %@", searchBar.text!).sorted(byKeyPath: "nameOfExercise", ascending: true)

下次调用该函数(即按退格键)时,将再次过滤新的,经过过滤的listOfExercises。您需要直接查询领域

listOfExercises = realm.objects(Exercise.self).("nameOfExercise CONTAINS[cd] %@", searchBar.text!)

或者,或者将原始列表的实例保存在您的类中,并对其进行查询。