我在UITableView的ContainerView中遇到UISearchBar(XCode 11,iOS 13,Swift 5)问题。在这里,我创建了一个UIView(searchView)和一个sortView彼此相邻,以便用户可以搜索和排序结果。

到目前为止,还没有问题,但是当我通过点击搜索栏的“取消”按钮结束搜索时,搜索栏会扩展到全屏宽度并与sortView重叠。

Situation before activating search

Situation with active search

Wrong behaviour after deactivating search

如何将搜索栏保留在其父视图(searchView)中?

我已经设置了一些限制来做到这一点,但没有成功。

也看一些代码:

func viewDidLoad() {
     ...

    searchController.searchBar.placeholder = "SR durchsuchen ..."
    searchController.searchBar.tintColor = UIColor.white
    searchController.dimsBackgroundDuringPresentation = false
    UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]).title = "Ende"
    searchController.hidesNavigationBarDuringPresentation = false
    searchController.searchBar.delegate = self

    searchView.addSubview(searchController.searchBar)

    ...
    }


override func viewDidLayoutSubviews() {

    self.searchController.searchBar.sizeToFit()

}

override func viewWillDisappear(_ animated: Bool) {

    self.searchController.definesPresentationContext = false
    self.searchController.isActive = false

}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    let searchTextField = self.searchController.searchBar.searchTextField
    searchTextField.textColor = UIColor(named: "searchFieldTextColor")
    searchTextField.leftView?.tintColor = UIColor(named: "searchFieldTextColor")

    searchController.searchBar.frame.size.width = searchView.frame.size.width
    searchController.searchBar.frame.size.height = searchView.frame.size.height

}

override func viewWillLayoutSubviews() {

    searchController.searchBar.frame = CGRect(x: 0, y: 0, width: searchView.frame.width, height: searchView.frame.height)
    searchController.searchBar.sizeToFit()

    let margins = searchView.layoutMarginsGuide
    searchController.searchBar.trailingAnchor.constraint(equalTo: margins.trailingAnchor, constant: 0).isActive = true
    searchController.searchBar.topAnchor.constraint(equalTo: margins.topAnchor, constant: 0).isActive = true
    searchController.searchBar.leadingAnchor.constraint(equalTo: margins.leadingAnchor, constant: 0).isActive = true
    searchController.searchBar.bottomAnchor.constraint(equalTo: margins.bottomAnchor, constant: 0).isActive = true
}

最佳答案

将这些方法称为UISearchControllerDelegate:

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

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

10-08 07:17