ios - UISearchController 在 iOS 13 上无法正常工作

标签 ios swift uisearchcontroller ios13

当设备在 iOS 13 上旋转时,我在 UISearchController 上遇到问题。

我有一个 tableView,这个 tableView 有一个 searchBar 作为标题。在 iOS 13 发布之前,此功能一直正常工作,现在旋转设备上出现了不需要的行为。

如果设备处于纵向方向并且搜索栏处于焦点状态,那么我将设备旋转到横向方向,则搜索栏不在正确的位置;正如您在下图中看到的,搜索栏必须位于黄色 View 中,但它有点低于它

enter image description here

但是当按下取消按钮时,搜索栏会转到正确的位置。

enter image description here

我已经对其进行了调试,并且 View 似乎是在正确的位置创建的,包括框架大小和原点。

当焦点位于搜索栏上并且方向为横向然后更改为纵向时,会发生类似的行为。

我添加搜索栏的代码:

func setupSearchBar() {
    searchController.searchResultsUpdater = self
    searchController.hidesNavigationBarDuringPresentation = false
    searchController.delegate = self
    searchController.definesPresentationContext = true
    searchController.searchBar.returnKeyType = UIReturnKeyType.done
    searchController.searchBar.placeholder = "search here ..."
    searchController.searchBar.tintColor = UIColor.red
    searchController.searchBar.delegate = self

    let yellowView: UIView = UIView.init(frame: searchController.searchBar.frame)
    yellowView.backgroundColor = UIColor.yellow
    yellowView.addSubview(searchController.searchBar)

    tableView.tableHeaderView = yellowView
    tableView.reloadData()
}

最佳答案

我通过创建自定义 UISearchController 解决了这个问题。

class CustomSearchController: UISearchController {

    var _searchBar: UISearchBar = UISearchBar.init()
    override var searchBar: UISearchBar {
        get { 
            return _searchBar 
        }

        set { 
            _searchBar = newValue 
        }
    }

}

我没有使用 UISearchController 提供的默认 UISearchBar,而是通过添加到 tableView 的新 UISearchBar 覆盖它。

enter image description here

func setupSearchBar() {
    searchController.searchBar = searchBar
    searchController.searchResultsUpdater = self
    searchController.hidesNavigationBarDuringPresentation = false
    searchController.delegate = self
    searchController.definesPresentationContext = true
    searchController.searchBar.returnKeyType = UIReturnKeyType.done
    searchController.searchBar.placeholder = "search here ..."
    searchController.searchBar.tintColor = UIColor.red
    searchController.searchBar.delegate = self

    tableView.tableHeaderView = searchController.searchBar
}

此解决方案适用于 iOS 9 或更高版本,并保留应用程序以前的行为。

关于ios - UISearchController 在 iOS 13 上无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58191878/

相关文章:

ios - 是否可以创建一个包含 4 个部分的 uitableview,但第一部分没有单元格

ios - 使用 PrivateFrameworkHeader-iOS-iPhone-5 API

ios - 递归函数,带有完成 block ,检索多个 MKDirections - Swift

ios - 从 UISearchController 过滤的搜索结果中删除

ios - 沙盒应用内购买,产品请求有效但购买总是失败

iphone - ARC 是否意味着我应该声明静态类型而不是 id?

ios - Swift Data(contentsOf) 参数传递给不带参数的调用

ios - 如何在自定义 UITableViewCell 按钮和第二个 View 之间创建一个 segue

ios - 多选快速搜索

swift - TVOS : Adjust the position of searchbar in UISearchViewController