Attempting to load the view of a view controller while it is deallocating… UISearchController

前端 未结 13 1111
一生所求
一生所求 2020-12-01 02:34

I have code that creates a UISearchController\' in my UIVIew\'sviewDidLoad`.

 self.resultSearchController = ({
        let controller = UISearch         


        
相关标签:
13条回答
  • 2020-12-01 03:18

    Creating a search controller in viewDidLoad() and setting its search bar as the navigation item's title view doesn't create a strong reference to the search controller, which is why it's deallocated.

    So instead of doing this:

    override func viewDidLoad() {
        super.viewDidLoad()
        // Create search controller
        let searchController = UISearchController(searchResultsController: nil)
        // Add search bar to navigation bar
        navigationItem.titleView = searchController.searchBar
        // Size search bar
        searchController.searchBar.sizeToFit()
    }
    

    You should do this:

    var searchController: UISearchController!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Create search controller
        searchController = UISearchController(searchResultsController: nil)
        // Add search bar to navigation bar
        navigationItem.titleView = searchController.searchBar
        // Size search bar
        searchController.searchBar.sizeToFit()
    }
    
    0 讨论(0)
提交回复
热议问题