一尘不染

如何更改UISearchBar占位符和图像色调颜色?

swift

我已经尝试了几个小时的搜索结果,但无法弄清楚。也许是不可能的。我正在尝试更改占位符文本和UISearchBar的放大镜的色调颜色。如果这很重要,我只针对iOS
8.0+。这是我的代码及其现在的样子:

let searchBar = UISearchBar()
searchBar.placeholder = "Search"
searchBar.searchBarStyle = UISearchBarStyle.Minimal
searchBar.tintColor = UIColor.whiteColor()

忙碌的猫

我希望搜索和放大镜是白色,或者是深绿色。


阅读 310

收藏
2020-07-07

共1个答案

一尘不染

如果您有可以使用的自定义图像,则可以使用类似于以下内容的方式设置图像并更改占位符文本颜色:

[searchBar setImage:[UIImage imageNamed:@"SearchWhite"] forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];

UITextField *searchTextField = [searchBar valueForKey:@"_searchField"];    
if ([searchTextField respondsToSelector:@selector(setAttributedPlaceholder:)]) {
    UIColor *color = [UIColor purpleColor];
    [searchTextField setAttributedPlaceholder:[[NSAttributedString alloc] initWithString:@"Search" attributes:@{NSForegroundColorAttributeName: color}]];
}

在该示例中,我使用了PurpleColor,而是可以使用该+ (UIColor *)colorWithRed:(CGFloat)red green:(CGFloat)green blue:(CGFloat)blue alpha:(CGFloat)alpha方法来创建自定义的深绿色。

编辑:我刚刚意识到你正在迅速写它…嗯。快速输入答案,这样我就不会只把答案留在Obj-C中了。

    searchBar.setImage(UIImage(named: "SearchWhite"), forSearchBarIcon: UISearchBarIcon.Search, state: UIControlState.Normal);

    var searchTextField: UITextField? = searchBar.valueForKey("searchField") as? UITextField
    if searchTextField!.respondsToSelector(Selector("attributedPlaceholder")) {
        var color = UIColor.purpleColor()
        let attributeDict = [NSForegroundColorAttributeName: UIColor.purpleColor()]
        searchTextField!.attributedPlaceholder = NSAttributedString(string: "search", attributes: attributeDict)
    }

斯威夫特3.0

    var searchTextField: UITextField? = searchBar.value(forKey: "searchField") as? UITextField
    if searchTextField!.responds(to: #selector(getter: UITextField.attributedPlaceholder)) {
        let attributeDict = [NSForegroundColorAttributeName: UIColor.white]
        searchTextField!.attributedPlaceholder = NSAttributedString(string: "Search", attributes: attributeDict)
    }
2020-07-07