49

有没有人知道如何更改 UISearchBar 的占位符文本的文本颜色的任何想法或代码示例?

4

18 回答 18

81

使用iOS5+外观代理

[[UILabel appearanceWhenContainedIn:[UISearchBar class], nil] setTextColor:[UIColor redColor]];
于 2013-07-02T10:02:14.787 回答
30

以编程方式从更改 UITextField 的占位符文本颜色中找到答案

// Get the instance of the UITextField of the search bar
UITextField *searchField = [searchBar valueForKey:@"_searchField"];

// Change search bar text color
searchField.textColor = [UIColor redColor];

// Change the search bar placeholder text color
[searchField setValue:[UIColor blueColor] forKeyPath:@"_placeholderLabel.textColor"];
于 2012-09-13T16:55:22.353 回答
20

第一个解决方案还可以,但是如果您使用多个 UISearchBar,或者创建很多实例,它可能会失败。始终对我有用的一种解决方案是也使用外观代理,但直接在 UITextField

   NSDictionary *placeholderAttributes = @{
                                            NSForegroundColorAttributeName: [UIColor darkButtonColor],
                                            NSFontAttributeName: [UIFont fontWithName:@"HelveticaNeue" size:15],
                                            };

    NSAttributedString *attributedPlaceholder = [[NSAttributedString alloc] initWithString:self.searchBar.placeholder
                                                                                attributes:placeholderAttributes];

    [[UITextField appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]] setAttributedPlaceholder:attributedPlaceholder];
于 2015-04-03T11:16:16.303 回答
18

这是 Swift 的解决方案:

斯威夫特 2

var textFieldInsideSearchBar = searchBar.valueForKey("searchField") as? UITextField
textFieldInsideSearchBar?.textColor = UIColor.whiteColor()

var textFieldInsideSearchBarLabel = textFieldInsideSearchBar!.valueForKey("placeholderLabel") as? UILabel
textFieldInsideSearchBarLabel?.textColor = UIColor.whiteColor()

斯威夫特 3

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

let textFieldInsideSearchBarLabel = textFieldInsideSearchBar!.value(forKey: "placeholderLabel") as? UILabel
textFieldInsideSearchBarLabel?.textColor = UIColor.white
于 2015-06-25T12:28:51.383 回答
9

试试这个看看:(我用 Swift 4.1 - Xcode 9.3-beta4测试了下面的代码)

@IBOutlet weak var sbSearchBar: UISearchBar!

if let textfield = sbSearchBar.value(forKey: "searchField") as? UITextField {

    textfield.backgroundColor = UIColor.yellow
    textfield.attributedPlaceholder = NSAttributedString(string: textfield.placeholder ?? "", attributes: [NSAttributedStringKey.foregroundColor : UIColor.red])

    textfield.textColor = UIColor.green

    if let leftView = textfield.leftView as? UIImageView {
        leftView.image = leftView.image?.withRenderingMode(.alwaysTemplate)
        leftView.tintColor = UIColor.red
    }
}

这是结果:

在此处输入图像描述

于 2018-03-15T14:16:26.103 回答
7
if let textFieldInsideSearchBar = searchBar.value(forKey: "searchField") as ? UITextField {
    textFieldInsideSearchBar ? .textColor = UIColor.white

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

        if 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
}
于 2016-11-20T16:15:09.147 回答
5

斯威夫特 5 - iOS 13

那些被卡住的人让我告诉你它只会在 viewDidLayoutSubviews 中工作,而不是在 viewDidLoad

override func viewDidLayoutSubviews() {

    setupSearchBar(searchBar: YourSearchBar)

}

    func setupSearchBar(searchBar : UISearchBar) {

    searchBar.setPlaceholderTextColorTo(color: UIColor.white)        

   }

extension UISearchBar
{
    func setPlaceholderTextColorTo(color: UIColor)
    {
        let textFieldInsideSearchBar = self.value(forKey: "searchField") as? UITextField
        textFieldInsideSearchBar?.textColor = color
        let textFieldInsideSearchBarLabel = textFieldInsideSearchBar!.value(forKey: "placeholderLabel") as? UILabel
        textFieldInsideSearchBarLabel?.textColor = color
    }
}

快乐编码:)

于 2020-02-27T10:01:07.990 回答
4

看起来 Apple 不希望我们在UISearchBar课堂上使用占位符颜色。所以,让我们创建自己的占位符标签!

  • 没有子类化。
  • 适用于 iOS 13 SDK。
  • 只是一种无辜的解决方法。

在此处输入图像描述

let searchBar = searchController.searchBar
// ...
// Configure `searchBar` if needed
// ...

let searchTextField: UITextField
if #available(iOS 13, *) {
    searchTextField = searchBar.searchTextField
} else {
    searchTextField = (searchBar.value(forKey: "searchField") as? UITextField) ?? UITextField()
}

// Since iOS 13 SDK, there is no accessor to get the placeholder label.
// This is the only workaround that might cause issued during the review.
if let systemPlaceholderLabel = searchTextField.value(forKey: "placeholderLabel") as? UILabel {
    // Empty or `nil` strings cause placeholder label to be hidden by the search bar
    searchBar.placeholder = " "

    // Create our own placeholder label
    let placeholderLabel = UILabel(frame: .zero)

    placeholderLabel.text = "Search"
    placeholderLabel.font = UIFont.systemFont(ofSize: 17.0, weight: .regular)
    placeholderLabel.textColor = UIColor.blue.withAlphaComponent(0.5)

    systemPlaceholderLabel.addSubview(placeholderLabel)

    // Layout label to be a "new" placeholder
    placeholderLabel.leadingAnchor.constraint(equalTo: systemPlaceholderLabel.leadingAnchor).isActive = true
    placeholderLabel.topAnchor.constraint(equalTo: systemPlaceholderLabel.topAnchor).isActive = true
    placeholderLabel.bottomAnchor.constraint(equalTo: systemPlaceholderLabel.bottomAnchor).isActive = true
    placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
    placeholderLabel.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal)
} else {
    searchBar.placeholder = ""
}
于 2019-11-15T06:16:31.340 回答
3

斯威夫特 3

UILabel.appearance(whenContainedInInstancesOf: [UISearchBar.self]).textColor = UIColor.white
于 2017-02-01T18:27:06.247 回答
3

iOS 13

以前的解决方案可能不适用于 iOS 13,因为添加了新的 searchTextField,您可以在其上设置属性字符串。

我将其包装为类别:

@interface UISearchBar (AttributtedSetter)
- (void)setThemedPlaceholder:(NSString*)localizationKey;
@end

@implementation UISearchBar (AttributtedSetter)

- (void)setThemedPlaceholder:(NSString*)localizationKey {
    ThemeObject *currentTheme = [[ThemeManager standardThemeManager] currentTheme];
    self.searchTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:NSLocalizedString(localizationKey, @"") attributes:@{NSForegroundColorAttributeName : currentTheme.colorSearchBarText}];
}

@end
于 2019-10-23T08:07:51.460 回答
3

iOS 13

使用自定义搜索栏子类。

这也适用于(with )UISearchController内的 a 的一部分。UINavigationItemhidesSearchBarWhenScrolling = true

我们希望在应用代理后立即应用我们的更改,UIAppearance因为这些是最可能的根本原因:

class MySearchBar : UISearchBar {
    // Appearance proxies are applied when a view is added to a view hierarchy, so apply your tweaks after that:
    override func didMoveToSuperview() {
        super.didMoveToSuperview() // important! - system colors will not apply correctly on ios 11-12 without this

        let placeholderColor = UIColor.white.withAlphaComponent(0.75)
        let placeholderAttributes = [NSAttributedString.Key.foregroundColor : placeholderColor]
        let attributedPlaceholder = NSAttributedString(string: "My custom placeholder", attributes: placeholderAttributes)
        self.searchTextField.attributedPlaceholder = attributedPlaceholder
        
        // Make the magnifying glass the same color
        (self.searchTextField.leftView as? UIImageView)?.tintColor = placeholderColor
    }
}

// Override `searchBar` as per the documentation
private class MySearchController : UISearchController {
    private lazy var customSearchBar = MySearchBar()
    override var searchBar: UISearchBar { customSearchBar }
}

这需要相当长的时间才能正常工作......

于 2020-03-01T00:19:14.837 回答
3

从 iOS 13.0 开始很容易,您可以简单地使用搜索栏的searchTextField属性来更新占位符的属性属性。

self.searchController.searchBar.searchTextField.attributedPlaceholder =  NSAttributedString.init(string: "Search anything...", attributes: [NSAttributedString.Key.foregroundColor:UIColor.red])

一条线解决方案

于 2020-11-02T09:33:38.993 回答
2

试试这个:

[self.searchBar setValue:[UIColor whatever] forKeyPath:@"_searchField._placeholderLabel.textColor"];

您也可以在情节提要中进行设置,选择搜索栏,在用户定义的运行时属性下添加条目:

_searchField._placeholderLabel.textColor

类型颜色并选择您需要的颜色。

于 2015-01-26T14:29:04.283 回答
1

IOS 13上为我工作

searchBar.searchTextField.attributedPlaceholder = NSAttributedString(
    string: "Search something blabla",
    attributes: [.foregroundColor: UIColor.red]
)
于 2021-02-14T18:45:42.730 回答
0

在调查了几个答案后,我出来了,希望对您有所帮助

for (UIView *subview in searchBar.subviews) {
    for (UIView *sv in subview.subviews) {
        if ([NSStringFromClass([sv class]) isEqualToString:@"UISearchBarTextField"]) {

            if ([sv respondsToSelector:@selector(setAttributedPlaceholder:)]) {
                ((UITextField *)sv).attributedPlaceholder = [[NSAttributedString alloc] initWithString:searchBar.placeholder attributes:@{NSForegroundColorAttributeName: [UIColor whiteColor]}];
            }
            break;
        }
    }
}
于 2015-05-19T05:38:22.100 回答
0

此解决方案适用于 Xcode 8.2.1。使用 Swift 3.0。:

extension UISearchBar
{
    func setPlaceholderTextColorTo(color: UIColor)
    {
        let textFieldInsideSearchBar = self.value(forKey: "searchField") as? UITextField
        textFieldInsideSearchBar?.textColor = color
        let textFieldInsideSearchBarLabel = textFieldInsideSearchBar!.value(forKey: "placeholderLabel") as? UILabel
        textFieldInsideSearchBarLabel?.textColor = color
    }
}

使用示例:

searchController.searchBar.setPlaceholderTextColorTo(color: mainColor)
于 2017-02-24T10:43:00.233 回答
-1

这是一个老问题,但对于现在遇到这个问题的人来说,您可以使用以下命令更改iOS 8.x - 10.3上的搜索图标:

[_searchBar setImage:[UIImage imageNamed:@"your-image-name"] forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];

关于占位符文本颜色,您可以查看我的另一个答案,它使用类别,在这里:UISearchBar change placeholder color

于 2017-06-02T12:51:54.607 回答
-3

试试这个:

  UITextField *searchField = [searchbar valueForKey:@"_searchField"];
  field.textColor = [UIColor redColor]; //You can put any color here.
于 2012-08-06T13:24:04.983 回答