OGeek|极客世界-中国程序员成长平台

标题: ios - 点击时 UISearchController 会在屏幕外展开 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 03:03
标题: ios - 点击时 UISearchController 会在屏幕外展开

在将 UISearchController 用作导航栏中的项目时,我们遇到了一个奇怪的问题。它被设置为左侧栏按钮项,当用户点击开始搜索时,搜索栏会扩展到屏幕右侧的右侧。

下面是创建 UISearchController 的代码:

resultSearchController = ({
    let controller = UISearchController(searchResultsController: nil)
    controller.searchResultsUpdater = self
    controller.dimsBackgroundDuringPresentation = false
    controller.hidesNavigationBarDuringPresentation = false
    controller.searchBar.delegate = self
    controller.delegate = self

    controller.searchBar.frame = CGRect(x: 0, y: 0, width: 266, height: 44.0)
    let searchBarView = UIView(frame: controller.searchBar.frame)
    searchBarView.addSubview(controller.searchBar)

    controller.searchBar.backgroundImage = UIImage(named: "searchBarBG")
    controller.searchBar.barTintColor = .white
    controller.searchBar.subviews[0].subviews.flatMap(){ $0 as? UITextField }.first?.tintColor = Constants.Colors.Red

    navigationItem.leftBarButtonItem = UIBarButtonItem(customView: searchBarView)

    return controller
})()

第一次加载屏幕时,它看起来像 this.

点击搜索栏后,它会变成 this.

我不知道是什么原因造成的。经过大量搜索,我尝试更改 self.definesPresentationContext = false;self.extendedLayoutIncludesOpaqueBars = true 以及调整 Storyboard 中的类似复选框。有什么建议吗?

编辑:这似乎只发生在 iOS 11 上。在 10.3 中,搜索栏实际上会缩小一点以容纳“取消”按钮,但最终占用的空间量相同。



Best Answer-推荐答案


我最终通过将 didPresentSearchControllerdidDismissSearchController 方法作为 UISearchControllerDelegate 的一部分来解决这个问题。

extension ContactUsViewController: UISearchControllerDelegate {

    func didPresentSearchController(_ searchController: UISearchController) 
    {
        searchController.searchBar.frame = CGRect(x: 0, y: 0, width: 266, height: 44.0)
    }

    func didDismissSearchController(_ searchController: UISearchController) 
    {
        searchController.searchBar.frame = CGRect(x: 0, y: 0, width: 266, height: 44.0)
    }
}

关于ios - 点击时 UISearchController 会在屏幕外展开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47079253/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4