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

Ios 如何更改UISearchBar占位符和图像着色颜色?,ios,iphone,xcode,swift,uikit,Ios,Iphone,Xcode,Swift,Uikit,我已经尝试了几个小时的搜索结果,但我无法弄明白这一点。也许这是不可能的。我正在尝试更改占位符文本的色调和UISearchBar的放大镜。如果有必要的话,我只针对iOS 8.0+。下面是我的代码和它现在的样子: let searchBar = UISearchBar() searchBar.placeholder = "Search" searchBar.searchBarStyle = UISearchBarStyle.Minimal searchBar.tintColor = UIColor.

我已经尝试了几个小时的搜索结果,但我无法弄明白这一点。也许这是不可能的。我正在尝试更改占位符文本的色调和UISearchBar的放大镜。如果有必要的话,我只针对iOS 8.0+。下面是我的代码和它现在的样子:

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


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

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

[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:(CGFloat)red:(CGFloat)green:(CGFloat)blue alpha:(CGFloat)alpha
方法来创建自定义的深绿色

编辑:我刚意识到你是用swift写的。。。嗯。很快就把它打出来了,所以我没有把答案留在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)
    }
Swift 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)
    }

您可以在不违反专用api规则的情况下更改文本的颜色:

UILabel.appearanceWhenContainedInInstancesOfClasses([UITextField.self]).textColor = UIColor.whiteColor()

我找到了一种方法来更改搜索栏中的文本字段。 它在swift 3和Xcode8中工作

首先,对UISearchBar类进行子类化

class CustomSearchBar: UISearchBar {
UISearchBar包含一个视图,其中包含所需的重要文本字段。下面的函数获取子视图中的索引

func indexOfSearchFieldInSubviews() -> Int! {
    var index: Int!
    let searchBarView = subviews[0]
    for (i, subview) in searchBarView.subviews.enumerated() {
        if subview.isKind(of: UITextField.self) {
            index = i
            break
        }
    }
    return index
}


override func draw(_ rect: CGRect) {
    // Find the index of the search field in the search bar subviews.
    if let index = indexOfSearchFieldInSubviews() {
        // Access the search field
        let searchField: UITextField = subviews[0].subviews[index] as! UITextField
        // Set its frame.
        searchField.frame = CGRect(x: 5, y: 5, width: frame.size.width - 10, height: frame.size.height - 10)
        // Set the font and text color of the search field.
        searchField.font = preferredFont
        searchField.textColor = preferredTextColor

        // Set the placeholder and its color
        let attributesDictionary = [NSForegroundColorAttributeName: preferredPlaceholderColor.cgColor]
        searchField.attributedPlaceholder = NSAttributedString(string: preferredPlaceholder, attributes: attributesDictionary)

        // Set the background color of the search field.
        searchField.backgroundColor = barTintColor
    }

    super.draw(rect)
}

好了,尽情享受吧。

Swift 3:如果你想更改占位符、clearbutton和放大镜

    let textFieldInsideSearchBar = searchBar.value(forKey: "searchField") as? UITextField
    textFieldInsideSearchBar?.textColor = UIColor.white

    let textFieldInsideSearchBarLabel = textFieldInsideSearchBar!.value(forKey: "placeholderLabel") as? UILabel
    textFieldInsideSearchBarLabel?.textColor = UIColor.white

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

    let glassIconView = textFieldInsideSearchBar?.leftView as? UIImageView

    glassIconView?.image = glassIconView?.image?.withRenderingMode(.alwaysTemplate)
    glassIconView?.tintColor = UIColor.white
细节
  • Xcode版本11.0(11A420a),iOS 13,swift 5
解决方案 全样本 结果

我无法使用上述任何解决方案使其正常工作

我创建了以下UISearchBar类别,可在iOS 8.4和10.3上正常工作:

[mySearchBar setPlaceholderColor:[UIColor redColor]];
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    [searchBar setPlaceholderColor:[UIColor redColor]];
}
ui搜索栏+占位符颜色.h

#import <UIKit/UIKit.h>

@interface UISearchBar (PlaceholderColor)

- (void)setPlaceholderColor:(UIColor *)placeholderColor;

@end
用法

[mySearchBar setPlaceholderColor:[UIColor redColor]];
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    [searchBar setPlaceholderColor:[UIColor redColor]];
}
重要提示:

确保在将UISearchBar添加到视图并创建其视图层次结构后调用SetPlaceholder Color:

如果以编程方式打开搜索栏,请在becomeFirstResponder调用后调用它,如下所示:

[mySearchBar becomeFirstResponder];
[searchBar setPlaceholderColor:[UIColor redColor]];
否则,如果您正在利用UISearchBarDelegate

[mySearchBar setPlaceholderColor:[UIColor redColor]];
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    [searchBar setPlaceholderColor:[UIColor redColor]];
}

Vasily Bodnarchuk伟大答案的小更新

斯威夫特4+


NSForegroundColorAttributeName
已更改为
NSAttributedStringKey。foregroundColor

对于任何试图更改文本但在查看更新的占位符时遇到问题的人,它通过将其放在此处而不是
viewDidLoad
对我起到了作用

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    self.searchBar.placeholder = @"My Custom Text";
}

在Swift 4中,假设您的搜索控制器设置如下:

let searchController = UISearchController(searchResultsController: nil)
然后设置占位符文本,如下所示:

searchController.searchBar.placeholder = "Here is my custom text"

我做了一个Swift 4.1搜索栏扩展:

import Foundation
import UIKit
extension UISearchBar{
    func setTextField(placeHolderColor:UIColor = .gray,placeHolder:String = "Search Something",textColor:UIColor = .white,backgroundColor:UIColor = .black,
                      placeHolderFont:UIFont = UIFont.systemFont(ofSize: 12.0),
                      textFont:UIFont =  UIFont.systemFont(ofSize: 12.0) ){
        for item in self.subviews{
            for mainView in (item as UIView).subviews{
                mainView.backgroundColor = backgroundColor
                if mainView is UITextField{
                    let textField = mainView as? UITextField
                    if let _textF = textField{
                        _textF.text = "success"
                        _textF.textColor = textColor
                        _textF.font      = textFont
                        _textF.attributedPlaceholder = NSMutableAttributedString.init(string: placeHolder, attributes: [NSAttributedStringKey.foregroundColor : placeHolderColor,
                                                                                                                               NSAttributedStringKey.font : placeHolderFont])
                    }
                }
            }
        }
    }
}
您可以将其用于
搜索栏
,如下所示:

controller.searchBar.setTextField(placeHolderColor: .white,
 placeHolder: "Search A Pet",
 textColor: .white,
 backgroundColor: .green,
 placeHolderFont: UIFont.systemFont(ofSize: 14.0),
 textFont: UIFont.systemFont(ofSize: 14.0))

刚找到这条线,很抱歉,因为时间太久了。然而,它帮助我解决了我的问题,在@m_katsifarakis的答案上添加了更多内容,我在他现有的类别中添加了更多内容

为占位符和输入文本添加额外的颜色+字体支持

仅在iOS 13上测试,因为这是我支持的全部

@interface UISearchBar (ColorandFont)
- (void)setPlaceholderColor:(UIColor *)placeholderColor setPlaceholderFont:(UIFont *)placeholderFont;
- (void)setTextColor:(UIColor *)textColor setTextFont:(UIFont *)textFont;
@end
@implementation UISearchBar (ColorandFont)

//Placeholder Color
- (void)setPlaceholderColor:(UIColor *)placeholderColor setPlaceholderFont:(UIFont *)placeholderFont{
    UILabel *labelView = [self placeholderText:self];
    [labelView setTextColor:placeholderColor];
    [labelView setFont:placeholderFont];
}
- (UILabel *)placeholderText:(UIView *)view {
    for (UIView *v in [view subviews]) {
        if ([v isKindOfClass:[UILabel class]]) {
            return (UILabel *)v;
        }

        UIView *labelView = [self placeholderText:v];
        if (labelView) {
            return (UILabel *)labelView;
        }
    }
    return nil;
}

//Text Color
- (void)setTextColor:(UIColor *)textColor setTextFont:(UIFont *)textFont{
    UITextField *textView = [self searchBarText:self];
    [textView setTextColor:textColor];
    [textView setFont:textFont];
}
- (UITextField *)searchBarText:(UIView *)view {
    for (UIView *v in [view subviews]) {
        if ([v isKindOfClass:[UITextField class]]) {
            return (UITextField *)v;
        }

        UIView *textView = [self searchBarText:v];
        if (textView) {
            return (UITextField *)textView;
        }
    }
    return nil;
}
@end
用法(我在viewDidLoad和Display中使用)鉴于我当前的设置,结果可能会有所不同:

[self.searchBar setPlaceholderColor:[UIColor lightTextColor] setPlaceholderFont:[UIFont italicSystemFontOfSize:13]];
[self.searchBar setTextColor:[UIColor whiteColor] setTextFont:[UIFont systemFontOfSize:16]];

这太完美了,非常感谢你。我没有看到
searchBar.valueForKey(“searchField”)是什么?UITextField
之前,这是一个很好的例子。有没有可能你也知道如何更改“清除”按钮(小圆x)?我想这将与设置图像的方式相同,但不是使用UISearchBarIcon.Search,而是使用.clear???不过我还没试过。除此之外,我知道实际的“取消”一词会受到搜索栏的影响。tintColor…访问私有属性或API肯定会让你的应用被拒绝。不要使用私有APIsAppearance当ContainedInstancesOfClass仅在ios9+中可用时,你有这方面的源代码吗?我很难理解这个。嗨@ethanfox27,这是源代码,希望能得到帮助。self.searcBar.setTextFieldColor(颜色:。白色)不工作为什么?仍然显示浅灰色,但其他颜色工作,但白色不工作任何想法。。。。当SearchBar位于NavigationBar中时,我一直试图在iOS 11上实现这一点,但没有成功。有什么想法吗?你好,雷纳托。我不明白你的问题。您不能将搜索栏添加到导航栏?非常感谢!这个解决方案看起来很不错,但是对于
UISearchController
,您需要同时对
UISearchController
和它的
UISearchBar
进行子类化。即使如此,清晰的按钮颜色仍然不起作用。知道为什么吗?很好的解决方案!一个问题是,
ClearButtonColor
在iOS 12.0中不起作用。问题是如何更改颜色,而不是如何设置textseachControl.searchBar.placeholder=“”很好的解决方案!图标工作正常,但占位符文本对我来说不会改变。