3

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

Adeel Miraj
  • 2,472
  • 3
  • 22
  • 32
Martin
  • 89
  • 1
  • 7
  • And this is my project https://github.com/MartinSnow/ChinaWeather.git – Martin Oct 05 '17 at 02:19
  • 1
    Rather handle it than hiding it, the problem is that your code dont handle empty text or something – Tj3n Oct 05 '17 at 02:54
  • Possible duplicate of https://stackoverflow.com/questions/21522104/hide-uisearchbar-clear-text-button – Vini App Oct 05 '17 at 02:55
  • It's the "clearButton" (that what you were looking for, and there is already doc/question about it). Now, as suggested by @Tj3n the real issue is that your code doesn't manage some case. I would strongly suggest to fix that first, then hide the clearbutton if you want to. – Larme Oct 05 '17 at 15:04

2 Answers2

3

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 */ }
}
Sam
  • 5,342
  • 1
  • 23
  • 39
  • 1
    just because you don't know how to translate obj-c to swift, does not make the answer invalid lol. Just ask how to translate it and I will help. But since you down voted me without checking on the language help, not cool. – Sam Oct 05 '17 at 13:08
  • @Moritz the user never requested a Swift version, but I'm happy to supply one as I can see his code is swift. – Sam Oct 05 '17 at 14:57
2

Swift 5

hide the x icon within the UISearchBar:

UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).clearButtonMode = .never
Hudi Ilfeld
  • 1,905
  • 2
  • 16
  • 25