UISearchBar更改占位符颜色

时间:2012-08-06 11:44:26

标签: ios uisearchbar placeholder

有没有人知道如何更改UISearchBar的占位符文本的文本颜色?

19 个答案:

答案 0 :(得分:75)

iOS5+使用外观代理

[[UILabel appearanceWhenContainedIn:[UISearchBar class], nil] setTextColor:[UIColor redColor]];

答案 1 :(得分:30)

Change UITextField's placeholder text color programmatically

找到答案
// 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"];

答案 2 :(得分:14)

第一种解决方案没问题,但如果您使用多个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];

答案 3 :(得分:14)

这是Swift的解决方案:

Swift 2

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

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

Swift 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

答案 4 :(得分: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
}

答案 5 :(得分:3)

Swift 3

UILabel.appearance(whenContainedInInstancesOf: [UISearchBar.self]).textColor = UIColor.white

答案 6 :(得分:3)

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

快乐编码:)

答案 7 :(得分:3)

试试这个并看看:(我在下面的代码中测试了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
    }
}

结果如下:

enter image description here

答案 8 :(得分:2)

试试这个:

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

您也可以在故事板中设置它,选择搜索栏,在“用户定义的运行时属性”下添加条目:

_searchField._placeholderLabel.textColor

类型颜色,然后选择您需要的颜色。

答案 9 :(得分:2)

iOS 13

使用自定义搜索栏。

UISearchControllerUINavigationItem的一部分(带有hidesSearchBarWhenScrolling = 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 }
}

花了很多时间才能正常工作...

答案 10 :(得分:2)

从iOS 13.0开始,这很容易,您只需使用搜索栏的 searchTextField 属性即可更新占位符的属性。

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

一线解决方案

答案 11 :(得分:1)

UISearchBar类中,Apple似乎不希望我们使用占位符颜色。因此,让我们创建自己的占位符标签!

  • 没有子类。
  • 使用iOS 13 SDK。
  • 一种无害的解决方法。

enter image description here

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 = ""
}

答案 12 :(得分:1)

这是一个旧帖子,但请查看此帖子以获得适当的解决方案 iPhone UITextField - Change placeholder text color

答案 13 :(得分:1)

IOS 13

上为我工作
searchBar.searchTextField.attributedPlaceholder = NSAttributedString(
    string: "Search something blabla",
    attributes: [.foregroundColor: UIColor.red]
)

答案 14 :(得分: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;
        }
    }
}

答案 15 :(得分: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)

答案 16 :(得分:0)

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

答案 17 :(得分:-1)

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

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

关于占位符文字颜色,您可以在此处查看我使用类别的其他答案:UISearchBar change placeholder color

答案 18 :(得分:-2)

试试这个:

  UITextField *searchField = [searchbar valueForKey:@"_searchField"];
  field.textColor = [UIColor redColor]; //You can put any color here.