我试图将searchBar设置为viewDidLoad中的tableHeaderView:
原文链接:https://www.f2er.com/swift/319549.htmloverride 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 }
成功!工作正常我不明白有什么区别?