tvOS UISearchController-滚动时如何避免自动的SearchBar和键盘隐藏行为?

时间:2020-05-14 15:34:43

标签: uikit uisearchbar tvos uisearchcontroller uikeyboard

在我的应用程序中,我根据为Apple提供的示例项目UIKitCatalog实现了UISearchController,此处为代码:

    /*
         A method demonstrating how to encapsulate a `UISearchController` for presentation in, for example, a `UITabBarController`
    */
    func packagedSearchController() -> UIViewController {
        // Load a `SearchResultsViewController` from its storyboard.
        let storyboard = UIStoryboard(name: "ViewControllerSamples", bundle: nil)
        guard let searchResultsController = storyboard.instantiateViewController(withIdentifier: SearchResultsViewController.storyboardIdentifier) as? SearchResultsViewController else {
            fatalError("Unable to instatiate a SearchResultsViewController from the storyboard.")
        }

        /*
            Create a UISearchController, passing the `searchResultsController` to
            use to display search results.
        */
        let searchController = UISearchController(searchResultsController: searchResultsController)
        searchController.searchResultsUpdater = searchResultsController
        searchController.searchBar.placeholder = NSLocalizedString("Enter keyword (e.g. iceland)", comment: "")

        // Contain the `UISearchController` in a `UISearchContainerViewController`.
        let searchContainer = UISearchContainerViewController(searchController: searchController)
        searchContainer.title = NSLocalizedString("Search", comment: "")

        // Finally contain the `UISearchContainerViewController` in a `UINavigationController`.
        let searchNavigationController = UINavigationController(rootViewController: searchContainer)
        return searchNavigationController
    }

此实现在我的应用程序中很好用,但是要避免使用SearchBar和Keyboard的自动隐藏行为,这可能吗?以及如何?

1 个答案:

答案 0 :(得分:1)

我对此问题进行了很多搜索,发现所有结果都是覆盖变量disablesAutomaticKeyboardDismissal: Bool并使其返回true,但此方法不起作用

对我来说,唯一成功的解决方案是将精力集中在搜索栏上

class CustomeSearchController : UISearchController {
    
    override var preferredFocusEnvironments: [UIFocusEnvironment]{
        return [self.searchBar]
    }
        
    override func didUpdateFocus(in context: UIFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) {
        self.view.setNeedsFocusUpdate()
        self.view.updateFocusIfNeeded()
    }
}

我希望这会有所帮助