Swift:SearchBar在parentViewController

时间:2015-11-22 13:01:42

标签: ios swift uisearchbar

我正在使用searchBar,当我选择搜索时,它工作得很好(除了这个运行时警告,我无法修复Attempting to load the view of a view controller while it is deallocating... UISearchController

但是如果searchBar isActive并且我从NavBar按“Back”,则会显示parentView,但上一个屏幕中的searchBar也是可见的。如果按下“后退”按钮,我尝试解除searchBar,但它仍然可见一段时间。我正在考虑

self.navigationItem.backButtonItem.enabled = false  

虽然searchBar处于活动状态,但我不喜欢这个解决方案

我的代码(我还有func updateSearchResultsForSearchController):

class ViewController: UIViewController ,UISearchResultsUpdating {
var resultSearchController = UISearchController()

override func viewDidLoad() {
        super.viewDidLoad()

        if #available(iOS 9.0, *) {
            self.resultSearchController.loadViewIfNeeded()// iOS 9
        } else {
            // Fallback on earlier versions
            let _ = self.resultSearchController.view// iOS 8
        }
        self.resultSearchController = ({
            let controller = UISearchController(searchResultsController: nil)
            controller.searchResultsUpdater = self
            controller.dimsBackgroundDuringPresentation = false
            controller.searchBar.sizeToFit()
            controller.hidesNavigationBarDuringPresentation = false
            self.tableView.tableHeaderView = controller.searchBar
            return controller
        })()

运行时警告(不确定这是否是问题)

Attempting to load the view of a view controller while it is deallocating is not allowed and may result in undefined behavior (<UISearchController: 0x7ff88130fdb0>)

2 个答案:

答案 0 :(得分:0)

要删除警告,请更改以下代码:

var resultSearchController = UISearchController()

为:

var resultSearchController : UISearchController!

并在viewWillDisappear方法中解除了您的resultSearchController

答案 1 :(得分:0)

感谢UISearchController - Warning Attempting to load the view of a view controller

请尝试以下操作:

class ViewController: UIViewController ,UISearchResultsUpdating {
var resultSearchController : UISearchController!

override func viewDidLoad() {
        super.viewDidLoad()


        self.resultSearchController = ({
            let controller = UISearchController()
            controller.searchResultsUpdater = self
            controller.dimsBackgroundDuringPresentation = false
            controller.searchBar.sizeToFit()
            controller.hidesNavigationBarDuringPresentation = false
            self.tableView.tableHeaderView = controller.searchBar
            return controller
        })()
    }
    deinit {
           self.searchController.loadViewIfNeeded()    // iOS 9
           let _ = self.searchController.view          // iOS 8
    }