Reputation: 429
I am trying to follow-up with this tutorial on CodePath: Visit https://guides.codepath.com/ios/Search-Bar-Guide#cancelling-out-of-search-and-hiding-keyboard
I created a SearchViewController to search but then didSelectRowAt doesn't work
This is my code below:
class SearchViewController: UIViewController, UITableViewDataSource, UISearchBarDelegate {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var searchBar: UISearchBar!
let data = ["New York, NY", "Los Angeles, CA", "Chicago, IL", "Houston, TX",
"Philadelphia, PA", "Phoenix, AZ", "San Diego, CA", "San Antonio, TX",
"Dallas, TX", "Detroit, MI", "San Jose, CA", "Indianapolis, IN",
"Jacksonville, FL", "San Francisco, CA", "Columbus, OH", "Austin, TX",
"Memphis, TN", "Baltimore, MD", "Charlotte, ND", "Fort Worth, TX"]
var filteredData: [String]!
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.allowsSelection = true
searchBar.delegate = self
filteredData = data
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TableCell", for: indexPath) as UITableViewCell
cell.textLabel?.text = filteredData[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return filteredData.count
}
// THIS IS NOT WORKING
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("didSelectRowAt(\(indexPath)")
}
// This method updates filteredData based on the text in the Search Box
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
// When there is no text, filteredData is the same as the original data
// When user has entered text into the search box
// Use the filter method to iterate over all items in the data array
// For each item, return true if the item should be included and false if the
// item should NOT be included
filteredData = searchText.isEmpty ? data : data!.filter { (item: String) -> Bool in
// If dataItem matches the searchText, return true to include it
return item.range(of: searchText, options: .caseInsensitive, range: nil, locale: nil) != nil
}
tableView.reloadData()
}
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
self.searchBar.showsCancelButton = true
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchBar.showsCancelButton = false
searchBar.text = ""
searchBar.resignFirstResponder()
}
}
Is there something else I need to do? The tutorial doesn't show any other code I was missing.
Upvotes: 1
Views: 401
Reputation: 116
In Your viewDidLoad() method
tableView.delegate = self
tableView.dataSource = self
Upvotes: 1
Reputation: 469
You should the UITableViewDelegate
delegate to your class and tableView.delegate = self
in your viewDidLoad
function. This will help to trigger the delegates functions of the UITableViewController
.
Upvotes: 5