I have a TableView with simple data in it. I have added SearchBar to the Navigation controller by code. (Not sure have i done proper way or not, but it is working). This is how it looks:
Code is below:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
var data = ["Hello","This","Is","Table","View","With","Search","Bar","Included","In","NavBar","But","SearchBar","Is","Not","Done","Properly"]
var filtered = [String]()
override func viewDidLoad() {
super.viewDidLoad()
//My original array and filtered arrays.
filtered = data
// Here a play with preferences add/delete
let searchBar = UISearchController(searchResultsController: nil)
navigationController?.navigationBar.prefersLargeTitles = true
navigationItem.searchController = searchBar
navigationItem.searchController?.dimsBackgroundDuringPresentation = false
navigationItem.searchController?.searchResultsUpdater = self
navigationItem.hidesSearchBarWhenScrolling = false
}
}
extension ViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return filtered.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
cell.textLabel?.text = filtered[indexPath.row]
return cell
}
}
extension ViewController: UISearchResultsUpdating {
func updateSearchResults(for searchController: UISearchController) {
if searchController.searchBar.text! == "" {
filtered = data
}
else {
filtered = data.filter {$0.lowercased().contains(searchController.searchBar.text!.lowercased())}
}
self.tableView.reloadData()
}
}
As you see i have done it by creating SearchController and then adding it to a NavController. Also implemented delegate UISearchResultsUpdating method to search and filter.
I have tried several ways but i do not know how to access to properties of SearchBar and NavController. (not by storyboard)
Some screenshots:
After like a day of search and try, i am not actually sure about it, as some methods work but some not. As example:
This works:
navigationItem.searchController?.searchBar.tintColor = .white
This does not work:
navigationItem.searchController?.searchBar.barTintColor = .red
So why can i access to one property and cannot to other? It is a very simple functionality, but tricky to find.
Maybe you could provide me some resource i could use for my case, as indicated in Images? Or if you have a time - some solution, maybe root example.
Thanks in advance.
Will continue to search.