I want to remove the clear button (gray x) from the UISearchBar. I tried to do it like described in this answer, but it doesn't work.
I translated the Objective-C code from the answer and the comment below to following Swift code:
for subview in searchBar.subviews {
configureSearchBarView(subview as UIView)
}
func configureSearchBarView(view: UIView) {
for subview in view.subviews {
self.configureSearchBarView(subview as UIView)
}
if subview.conformsToProtocol(UITextInputTraits) {
var clearView = view as UITextField
clearView.clearButtonMode = UITextFieldViewMode.Never
}
}
Unfortunatly this doesn't remove the clear button.
Another answer suggests to work with appearanceWhenContainedIn
, but this method doesn't seem to be implemented in Swift.
Any ideas?
Swift
I found a better way that completely removes the button, using clearButtonMode = .never
let searchBarStyle = searchBar.value(forKey: "searchField") as? UITextField
searchBarStyle?.clearButtonMode = .never
Tested on iOS 13
As I pointed out in another answer, this is the one liner working for me to make it disappear completely:
searchBar.searchTextField.clearButtonMode = .never
However you may also set it to .whileEditing
if you only want it displayed when the user is typing and then make it disappear when the search bar loses focus.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With