Прежде всего необходимо отфильтровать данные в textDidChange
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchText.isEmpty {
isSearching = false
view.endEditing(true)
filteredData.removeAll()
} else {
isSearching = true
filteredData = search.filter{ $0.songname.range(of: searchText, options: .caseInsensitive) != nil }
}
tableView.reloadData()
}
Затем необходимо изменить все методы источника данных, чтобы они отображали массив search
или filteredData
.
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return isSearching : search.count ? filteredData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! DataCell
let song = isSearching ? search[indexPath.row] : filteredData[indexPath.row]
cell.congigureCell(text: song.songname)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let searchSong = isSearching ? search[indexPath.row] : filteredData[indexPath.row]
let fileURLString = "\(filePath)\(searchSong.songname)"
print(fileURLString)
}
Примечание:
Необязательное связывание (if let cell
) в cellForRow
бессмысленно. В случае ошибки проектирования код взломает sh, и проблема может быть исправлена немедленно.