搜索栏在iOS中无法正常运行

时间:2016-10-08 18:46:28

标签: ios arrays swift uitableview uisearchbar

目前我正在我的项目中进行搜索功能,但它无法正常工作。目前,当我在UISearchbar中输入内容时,它确实会从搜索结果中更改,但它没有显示正确的搜索结果。这是因为数据中的单词之间有空格吗?因为当我使用单个单词时,它确实完美无缺。

数组和虚拟数据:

var exercises = [exercise]()
    var filteredExercises = [exercise]()

// SOME DUMMY DATA FOR THE TABLEVIEW
        let exercise1 = exercise(exerciseName: "Incline Bench Press")
        let exercise2 = exercise(exerciseName: "Decline Bench Press")
        let exercise3 = exercise(exerciseName: "Bench Press")

        exercises.append(exercise1)
        exercises.append(exercise2)
        exercises.append(exercise3)

搜索栏功能

// ***************** SEARCHBAR FUNCTIONS ************** //
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {

        if searchBar.text == nil || searchBar.text == "" {

            inSearchMode = false
            tableView.reloadData()

        }else{

            inSearchMode = true
            let lower = searchBar.text!.lowercased()


            // each exercise in array is $0 and we taking the name value and the range of the inserted text is that contained in the name
            filteredExercises = exercises.filter({$0.exerciseName.range(of: lower) != nil})
            tableView.reloadData()
        }
    }

在单元格中显示:

// ***************** TABLE DELEGATE FUNCTIONS ******************* //

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if let cell = tableView.dequeueReusableCell(withIdentifier: "exerciseCell", for: indexPath) as? exerciseCell {

//            let exercise = exercises[indexPath.row]

            let exer: exercise!

            if inSearchMode {

                print(filteredExercises)
                exer = filteredExercises[indexPath.row]
                cell.updateUI(exercise: exer)
            }else{

                exer = exercises[indexPath.row]
                cell.updateUI(exercise: exer)
            }

//            cell.updateUI(exercise: exercise)
            return cell
        }else{
            return UITableViewCell()
        }
}

希望有人看到问题。

2 个答案:

答案 0 :(得分:0)

问题是你在说:

let lower = searchBar.text!.lowercased()

exercises元素都是标题性的:

let exercise1 = exercise(exerciseName: "Incline Bench Press")
let exercise2 = exercise(exerciseName: "Decline Bench Press")
let exercise3 = exercise(exerciseName: "Bench Press")

...所以lower永远无法匹配exercises中的任何内容。

答案 1 :(得分:0)

您可以比较降低和降低的字符串。改为

filteredExercises = exercises.filter({$0.exerciseName.lowercased().range(of: lower) != nil})