Implementing UISearchBar with UITableView

45 Views Asked by At

So I have an app that lets users select movies from a list in tableview (populated by api), tapping on a movie presents a view with more details. I would like to implement a search bar so users can search for specific movies, however I am having some trouble

I assumed the following function would make movies searchable for the following tableview

 var newMovies: [NSDictionary] = []

...

 func searchBar() {

        let searchBar = UISearchBar(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 50))
        searchBar.delegate = self
        searchBar.showsScopeBar = true
        searchBar.tintColor = UIColor.lightGray
        self.tableView.tableHeaderView = searchBar
    }

    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        if searchText == "" {
            fetchMovies()
        }
        else {
            if searchBar.selectedScopeButtonIndex == 0 {
                newMovies = newMovies.filter({ (NSDictionary) -> Bool in
                    return NSDictionary.lowercased().contains(searchText.lowercased())
                })
            }
            else {

            }
        }
    }


 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{

        return newMovies.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {



        let cell = tableView.dequeueReusableCell(withIdentifier: "MovieCell", for: indexPath)  as! MovieSearchTableViewCell
        let movie =  newMovies[indexPath.row]
        let title = movie["title"] as! String
        let overview = movie["overview"] as! String

        cell.titleLabel.text = title
    cell.overviewLabel.text = overview

However this presents 2 errors on the line;

return NSDictionary.lowercased().contains(searchText.lowercased())

Value of type 'Any' has no member 'contains'

Value of type 'NSDictionary' has no member 'lowercased'

should I be returning something other than NSDictionary?

1

There are 1 best solutions below

0
Rob C On

Assuming you are searching for matching titles you would want to do this:

newMovies = newMovies.filter({ movie in
    guard let title = movie["title"] as? String else { return false }
    return title.lowercased().contains(searchText.lowercased())
})