更改UISearchbar放大镜颜色、占位符颜色和X颜色

5

我已经搜索了各种解决方案来完成这个任务,但它们要么是使用Objective C,要么涉及替换放大镜图像。

enter image description here

enter image description here

我之前查看过的文章:

更改放大镜颜色

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

我不想替换放大镜的图像,因为页面颜色是动态的,而且有100多种颜色组合

非常感谢任何关于更改UISearchbar放大镜颜色、占位符颜色和X颜色的帮助。


@Mr.T,我已经更改了tintcolor,它会改变输入文本和取消按钮的字体颜色,但不会影响占位符或X按钮。 - SlopTonio
你看过的帖子中有一个建议更改占位符颜色的方法,你试过了吗? - Teja Nandamuri
@Mr.T,我已经使用attributedtext属性成功实现了占位符文本颜色的更改。我还在尝试找出如何更改X和放大镜的方法。 - SlopTonio
看这个:https://dev59.com/nF4c5IYBdhLWcg3wapzz - Teja Nandamuri
@Mr.T,这是否被视为修改私有属性或API,从而导致我的应用程序被应用商店拒绝? - SlopTonio
显示剩余2条评论
3个回答

15

Objective C:

NSArray *searchBarSubViews = [[self.searchBar.subviews objectAtIndex:0] subviews];
for (UIView *view in searchBarSubViews) {
    if([view isKindOfClass:[UITextField class]])
    {
        UITextField *textField = (UITextField*)view;
        UIImageView *imgView = (UIImageView*)textField.leftView;
        imgView.image = [imgView.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
        imgView.tintColor = [UIColor whiteColor];

        UIButton *btnClear = (UIButton*)[textField valueForKey:@"clearButton"];
        [btnClear setImage:[btnClear.imageView.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forState:UIControlStateNormal];
        btnClear.tintColor = [UIColor whiteColor];

    }
}
[self.searchBar reloadInputViews];

Swift:

// Text field in search bar.
let textField = searchController.searchBar.valueForKey("searchField") as! UITextField

let glassIconView = textField.leftView as! UIImageView
glassIconView.image = glassIconView.image?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
glassIconView.tintColor = UIColor.whiteColor()

let clearButton = textField.valueForKey("clearButton") as! UIButton
clearButton.setImage(clearButton.imageView?.image?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate), forState: .Normal)
clearButton.tintColor = UIColor.whiteColor()

3

Shahil的答案已更新至Swift 3:

let textField = searchBar.value(forKey: "searchField") as! UITextField

let glassIconView = textField.leftView as! UIImageView
glassIconView.image = glassIconView.image?.withRenderingMode(.alwaysTemplate)
glassIconView.tintColor = .white


let clearButton = textField.value(forKey: "clearButton") as! UIButton
clearButton.setImage(clearButton.imageView?.image?.withRenderingMode(.alwaysTemplate), for: .normal)
clearButton.tintColor = .white

0
func setupPlaceHolder(text: String, textColor: UIColor) {
  searchBar.searchTextField.attributedPlaceholder = NSAttributedString(
    string: text,
    attributes: [.foregroundColor: textColor]
  )
        
  searchBar.searchTextField.leftView?.tintColor = .white
}

请修复您回答的格式。仅有代码的答案并不是非常有帮助的。最好解释一下代码的作用以及它如何解决问题。 - HangarRash

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接