1
votes

I want to customize the cancel button inside the UISearchBar, that appears when the user type a text, to clear the text, see the image, I want to change the tint color of the button inside the red square NOT the button with "cancel" text

What I have tried :

[[UIButton appearanceWhenContainedIn:[UISearchBar class], nil] setTintColor:[UIColor redColor]];

but it changes the color of the button with the text "cancel" not the icon to clear the text inside the textfield

it's not a duplicate question because I want to change the tint of the default clear image, NOT using a custom image, something like that :

How to change the tint color of the clear button on a UITextField

but for UISearchBar

enter image description here

2
check this question stackoverflow.com/questions/1200149/…user5917312
I am talking about the clear button the button with red squareiOSGeek
I am also getting the same issue clear button color is not changed.Deepak Saki

2 Answers

2
votes
UIImage *imgClear = [UIImage imageNamed:@"clear"];
[mySearchBar setImage:imgClear forSearchBarIcon:UISearchBarIconClear state:UIControlStateNormal];
1
votes

Swift 4.2, 4.1+

It seems that the currentImage is nil for clearButton from Swift 4.1+. It might be working in the older versions.

So i created this class and the addition here is to provide your own image and color for clear button.

class SearchBar: UISearchBar {

    var clearButtonImage: UIImage?
    var clearButtonColor: UIColor = .white

    override func layoutSubviews() {
        super.layoutSubviews()

        if let textField = self.value(forKey: "searchField") as? UITextField {
            if let clearButton = textField.value(forKey: "clearButton") as? UIButton {
                update(button: clearButton, image: self.clearButtonImage, color: clearButtonColor)
            }
        }
    }

    private func update(button: UIButton, image: UIImage?, color: UIColor) {
        let image = (image ?? button.currentImage)?.withRenderingMode(.alwaysTemplate)
        button.setImage(image, for: .normal)
        button.setImage(image, for: .highlighted)
        button.tintColor = color
    }
}

So now you can set the clearButton image as below to make it work,

let searchBar = SearchBar()
searchBar.clearButtonImage = UIImage(named: "clearIcon")
searchBar.clearButtonColor = .green

Storyboard or XIB

You have to set the SearchBar class as custom class for search bar shown below,

enter image description here

And outlet as below to set the images and colors etc

@IBOutlet private weak var searchBar: SearchBar!