Skip to content

Instantly share code, notes, and snippets.

@7foots
Last active March 18, 2020 09:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 7foots/996818aceb1c097e602eb42be09efa76 to your computer and use it in GitHub Desktop.
Save 7foots/996818aceb1c097e602eb42be09efa76 to your computer and use it in GitHub Desktop.
Quick access to cancel button in UISearchController
/**
Example for customize your cancel button:
let controller = UISearchController(searchResultsController: nil)
controller.searchBar.showsCancelButton = true
if let button = controller.cancelButton() {
// Customize button
let iconImage = UIImage(named: "icon")
button.isEnabled = true
button.setTitle("", for: .normal)
button.setBackgroundImage(iconImage, for: .normal)
button.addTarget(self, action: #selector(tap), for: .touchUpInside)
}
*/
extension UISearchController {
func cancelButton() -> UIButton? {
if #available(iOS 13.0, *) {
return findCancelButton13()
}
return findCancelButtonOld()
}
func findCancelButtonOld() -> UIButton? {
for subView in searchBar.subviews {
for v in subView.subviews {
if let button = v as? UIButton {
return button
}
}
}
return nil
}
@available(iOS 13.0, *)
func findCancelButton13() -> UIButton? {
for subView in searchBar.subviews {
for v in subView.subviews {
for b in v.subviews {
if let button = b as? UIButton {
return button
}
}
}
}
return nil
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment