I have tried to set the searchBar
as a tableHeaderView
inside of the viewDidLoad
:
override func viewDidLoad() {
super.viewDidLoad()
// SearchController initializiation
self.searchController = UISearchController.init(searchResultsController: nil)
self.searchController.delegate = self
self.searchController.searchBar.delegate = self
self.searchController.searchBar.sizeToFit()
self.searchController.searchResultsUpdater = self
self.searchController.searchBar.barTintColor = UIColor.white
self.searchController.searchBar.keyboardAppearance = .default
self.searchController.searchBar.backgroundColor = UIColor.white
self.searchController.hidesNavigationBarDuringPresentation = true
self.searchController.obscuresBackgroundDuringPresentation = false
self.tableView.tableHeaderView = self.searchController.searchBar
self.definesPresentationContext = true
self.fetch()
self.tableView.reloadData()
}
And this my fetch()
function:
func fetch() {
let fetchRequest:NSFetchRequest<Phone> = Phone.fetchRequest()
fetchRequest.sortDescriptors = [NSSortDescriptor.init(key: "header", ascending: true), NSSortDescriptor.init(key: "date", ascending: true)]
self.fetchedResultsController = NSFetchedResultsController.init(fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext, sectionNameKeyPath: "header", cacheName: nil)
self.fetchedResultsController.delegate = self
do {
try self.fetchedResultsController.performFetch()
self.tableView.reloadData()
} catch {}
}
But I don't understand they are doesn't work. The Xcode crashes and nothing actually happens. And then I have tried to change something inside of viewDidLoad
method:
override func viewDidLoad() {
super.viewDidLoad()
self.fetch()
self.tableView.reloadData()
// SearchController initializiation
self.searchController = UISearchController.init(searchResultsController: nil)
self.searchController.delegate = self
self.searchController.searchBar.delegate = self
self.searchController.searchBar.sizeToFit()
self.searchController.searchResultsUpdater = self
self.searchController.searchBar.barTintColor = UIColor.white
self.searchController.searchBar.keyboardAppearance = .default
self.searchController.searchBar.backgroundColor = UIColor.white
self.searchController.hidesNavigationBarDuringPresentation = true
self.searchController.obscuresBackgroundDuringPresentation = false
self.tableView.tableHeaderView = self.searchController.searchBar
self.definesPresentationContext = true
}
Success! Works properly. I don't understand what is the difference?
fetchedResultsController
is not nil? – EftaUISearchResultsUpdating
andUISearchBarDelegate
. The viewController is being set as delegate for two different objects (searchBar.delegate
andsearchResultsUpdater
) before the fetchedResultsController is setup. So it can get methods called by them immediately. If those methods assume that there is a fetchedResultsController setup it could cause a logical error. – Efta