5

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?

Apfelsaft
  • 5,766
  • 4
  • 28
  • 37

3 Answers3

7

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
CristianMoisei
  • 2,071
  • 2
  • 22
  • 28
  • 1
    Why the restoration ID? That doesn't have anything to do with it. – Sulthan Jun 09 '18 at 17:54
  • Hm, I thought that's how you identified the searchField. – CristianMoisei Jun 10 '18 at 20:18
  • 2
    Nope, that `searchField` is basically a hidden property `var searchField: UITextField` which we are accessing through key-value coding. Since it's hidden (undocumented) property, it can stop working on next iOS minor release. – Sulthan Jun 10 '18 at 20:23
6

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.

5

I found a solution. It is possible to exchange the clear button with a custom image:

UISearchBar.appearance().setImage(UIImage(named: "emptyImg"), forSearchBarIcon: UISearchBarIcon.Clear, state: UIControlState.Normal)
UISearchBar.appearance().setImage(UIImage(named: "emptyImg"), forSearchBarIcon: UISearchBarIcon.Clear, state: UIControlState.Highlighted)

emptyImg is an png that contains one white pixel. Found in this answer

Community
  • 1
  • 1
Apfelsaft
  • 5,766
  • 4
  • 28
  • 37