Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS10 How can I hide "x" symbol of the searchBar

I can display and hide keyboard. There is a problem: when I tap something in the searchBar, there is a X symbol in the left of the searchBar and a cancel button. If I click cancel button first and then click the X symbol, I will got an fatal error: Index out of range.

enter image description here

So I want to hide the “x” symbol rather than “cancel” button. Is this possible?

enter image description here

like image 522
Martin Avatar asked Sep 19 '25 23:09

Martin


2 Answers

Get the textfield and hide it.

UITextField *textField = [searchBar valueForKey:@"_searchField"];
textField.clearButtonMode = UITextFieldViewModeNever;

or Swift you can alwasy extend the search bar and override it.

class NoCancelButtonSearchController: UISearchController {
    let noCancelButtonSearchBar = NoCancelButtonSearchBar()
    override var searchBar: UISearchBar { return noCancelButtonSearchBar }
}

class NoCancelButtonSearchBar: UISearchBar {
    override func setShowsCancelButton(_ showsCancelButton: Bool, animated: Bool) { /* void */ }
}
like image 106
Sam Avatar answered Sep 22 '25 14:09

Sam


Swift 5

hide the x icon within the UISearchBar:

UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).clearButtonMode = .never
like image 45
Hudi Ilfeld Avatar answered Sep 22 '25 13:09

Hudi Ilfeld