Kevin Vugts Kevin Vugts - 1 month ago 15
Swift Question

Searchbar doesn't work properly in iOS

Currently I am making a search functionality in my project but it isn't working properly. Currently when I typ something in the UISearchbar it does change from search results but its not showing the correct search results. Is this because of the white space between the words in the data? Because when I use single words it does work perfect.

arrays and dummy data:

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 function:

// ***************** 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()
}
}


showing in the cell:

// ***************** 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()
}
}


Hope someone sees the problem.

Answer

The problem is that you are saying:

let lower = searchBar.text!.lowercased()

But the exercises elements are all titlecased:

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

... so lower can never match anything in exercises.

Comments