我尝试将searchBar
设置为tableHeaderView
内的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()
}
这是我的fetch()
功能:
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 {}
}
但我不明白他们没有工作。 Xcode崩溃,实际上什么都没发生。然后我试图改变viewDidLoad
方法中的内容:
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
}
成功!工作正常。我不明白有什么区别?
答案 0 :(得分:2)
您应该尝试从self.tableView.reloadData()
方法中删除viewDidLoad()
,因为数据甚至没有加载以重新加载。
答案 1 :(得分:1)
这是因为你甚至在初始化fetchedResultsController之前设置了searchResultsUpdater和searchBar的委托。在您的代码searchResultsUpdater或searchBar的委托方法中的某些位置正在访问您的fetchedResultsController并将其设置为nil,以便您应用程序崩溃。我的建议是避免崩溃是使searchResultsController成为计算或惰性属性。