I'm facing an issue with UISearchBar (XCode 11, iOS 13, Swift 5) inside ContainerView in a UITableView. There I created a UIView (searchView) and a sortView next to each other, so that the user can search and sort the results.
No problem so far, but when I end searching by tapping the cancel button of the searchbar, the searchbar expands to the full screen width and overlaps the sortView.
Situation before activating search
Wrong behaviour after deactivating search
How is it possible to keep the searchbar inside its superview (searchView)?
I've already set some constraints to do that but no success.
See some code, too:
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
}