1

I'm trying to change the colour of the clear button icon for my UISearchBar using the following code:

let searchField = searchBar.value(forKey: "searchField") as? UITextField
if let clearButton = searchField?.value(forKey: "clearButton") as? UIButton {
    clearButton.setImage(clearButton.imageView?.image?.withRenderingMode(.alwaysTemplate), for: .normal)
    clearButton.tintColor = .white
}

This doesn't work if called in viewDidLoad because the clear button isn't visible. How do I make this work?

Note: This is not related to the tinting of the cancel button or anything else as stated in the comments, just the clear button that looks like an x.

Tometoyou
  • 7,792
  • 12
  • 62
  • 108
  • 2
    Possible duplicate of [How to change the colour of the 'Cancel' button on the UISearchBar in Swift](https://stackoverflow.com/questions/35302760/how-to-change-the-colour-of-the-cancel-button-on-the-uisearchbar-in-swift) – Sandeep Bhandari Jun 18 '18 at 10:24
  • read the accepted answer and comments below it – Sandeep Bhandari Jun 18 '18 at 10:25
  • see this.. https://stackoverflow.com/questions/36542549/customize-search-bar/36543336#36543336 – Mahendra Jun 18 '18 at 10:26
  • Possible duplicate of [Customize search bar](https://stackoverflow.com/questions/36542549/customize-search-bar) – Mahendra Jun 18 '18 at 10:28
  • None of these supposed duplicates are related. They're to do with tinting the rest of the search bar, which I have all ready done. Mine question is specific to the clear button, not the cancel button. – Tometoyou Jun 18 '18 at 10:34
  • As per what I know, you can't change clear button's color, if you still want to change it, then you can use image of your choice to in place of clear button's actual image. – Mehul Thakkar Jun 18 '18 at 10:39
  • @MehulThakkar My code does change the colour of the clear button but only when used in `searchBarTextDidBeginEditing` – Tometoyou Jun 18 '18 at 10:40
  • If you want code for how to update clear button's image, then let me know. I can post the code. – Mehul Thakkar Jun 18 '18 at 10:40
  • @Tometoyou: I know that... I have also worked on this, 1-1.5 months ago, and it was not working as expected. Thats why, finally I updated the image of clear button and it worked as I expected it to be. – Mehul Thakkar Jun 18 '18 at 10:41
  • Did you find a solution? I have the same problem on iOS 12. – sluijs Mar 23 '19 at 10:03

0 Answers0