斯威夫特 如何在不上传新图像的情况下更改 UISearchBar 清除按钮颜色



我已经在寻找几个小时的答案了,但我仍然不知道如何更改UISearchBar清晰的按钮颜色(小灰色x十字)。

所有答案都解释了如何设置新的清除按钮图标,但我只想将其颜色更改为白色..即使我mySearchBar.barStyle更改为黑色,清除按钮也保持灰色。我可能没有检查过整个互联网,但这似乎是不可能的。

谢谢

您可以使用图标字体,为图像绘制字符串,并使用它来设置图标。我为此创建了一个扩展:

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)
    }
}

要使用它,您需要下载FontAwesome并将其作为用户字体添加到您的项目中,然后调用:

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

这样 UISearchBar 看起来像: https://www.dropbox.com/s/fx7dbtoxd785zo7/Screenshot%202015-05-12%2011.36.02.png?dl=0

要选择图标,请转到备忘单并将图标复制粘贴到源代码中:http://fortawesome.github.io/Font-Awesome/cheatsheet/

该扩展也是LSwift的一部分:http://superarts.github.io/LSwift/

相关内容

最新更新