Floki
Floki

Reputation: 23

Swift How to change UISearchBar clear button color without uploading a new image

I've been looking for an answer for hours now and I still can't figure out how to change an UISearchBar clear button color (the little grey x cross).

All answers explain how to set a new clear button icon but I just want to change its color to white.. even if I change mySearchBar.barStyle to black, the clear button stays grey. I may not have checked on the whole Internet but it just doesn't seem possible.

Thanks

Upvotes: 1

Views: 1417

Answers (1)

superarts.org
superarts.org

Reputation: 7238

You can use an icon font, draw a string to an image, and use it to set the icon. I've created an extension for this:

extension UISearchBar {
    func set_text_image(text: NSString, icon:UISearchBarIcon, attribute:LTDictStrObj? = nil, state:UIControlState = .Normal) {
        var textColor: UIColor = UIColor.whiteColor()
        var textFont: UIFont = UIFont(name: "FontAwesome", size: 15)!
        UIGraphicsBeginImageContext(CGSizeMake(15, 15))
        var attr = attribute
        if attr == nil {
            attr = [
                NSFontAttributeName: textFont,
                NSForegroundColorAttributeName: textColor,
            ]
        }
        text.drawInRect(CGRectMake(0, 0, 15, 15), withAttributes: attr)
        var image: UIImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        self.setImage(image, forSearchBarIcon:icon, state:state)
    }
}

To use it you need to download FontAwesome and add it to your project as a user font, and then call:

    search_bar.set_text_image("", icon:.Clear)
    search_bar.set_text_image("", icon:.Search)

So that the UISearchBar looks like: https://www.dropbox.com/s/fx7dbtoxd785zo7/Screenshot%202015-05-12%2011.36.02.png?dl=0

To choose an icon, go to the cheatsheet and copy-paste the icon into your source code: http://fortawesome.github.io/Font-Awesome/cheatsheet/

The extension is also a part of LSwift: http://superarts.github.io/LSwift/

Upvotes: 1

Related Questions