I read all questions on stackoverflow but none of them could solve my problem. I created a UICollectionView and and anchored a searchBar inside of the navigationBar without using Storyboards!
class UserSearchController: UICollectionViewController ,.. {..
lazy var searchBar: UISearchBar = {
let sb = UISearchBar()
sb.placeholder = "Enter username"
sb.barTintColor = UIColor.gray
UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).backgroundColor = UIColor.rgb(red: 230, green: 230, blue: 230)
sb.delegate = self
sb.showsCancelButton = true
return sb
}() ....
// adding the searchBar to the collectionView as subView and
anchoring it to the navigationBar
The searchbar is shown inside of the navigationBar and everything works fine. The problem occurs when I try to add a scopebar to my searchbar. I added the following properties to my searchbar
sb.showsScopeBar = true
sb.scopeButtonTitles = ["Username", "Hashtag"]
The scopeBar is hide behind the navigationBar and the navBar is not automatically increasing its height. You just see a gray background.
Adding my code to a simple UiViewController everything works fine
This code works inside a normal VIewController where the searchBar is added as subView and anchored to the view.
lazy var searchBar: UISearchBar = {
let sb = UISearchBar()
sb.placeholder = "Enter username"
sb.barTintColor = UIColor.gray
UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).backgroundColor = UIColor.rgb(red: 230, green: 230, blue: 230)
sb.delegate = self
sb.scopeButtonTitles = ["Username", "Hashtag"]
sb.tintColor = UIColor.black
sb.barTintColor = UIColor.lightGray
return sb
}()
public func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
searchBar.showsScopeBar = true
searchBar.sizeToFit()
searchBar.setShowsCancelButton(true, animated: true)
return true
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchBar.showsScopeBar = false
searchBar.endEditing(true)
}
My searchBar looks like the following. If you start typing the scopeBar appears and if you click cancel it disappears. I want the same but only inside of the navBar :
How is it possible to add a searchBar with scopeBar inside of the navigationBar without Storyboards. Isn't there any easy way. Please can you refer to my code and use my code to show me how this works. I also tried to increase the size of the navigationBar but it should work automatically and I don't know if this is the right approach.