Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove clear button in UISearchBar

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?

like image 372
Apfelsaft Avatar asked Dec 02 '22 19:12

Apfelsaft


2 Answers

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
like image 127
CristianMoisei Avatar answered Dec 20 '22 21:12

CristianMoisei


Swift 5

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.

like image 24
Luis Antonio Canettoli Ordoñez Avatar answered Dec 20 '22 21:12

Luis Antonio Canettoli Ordoñez