UISearchBar change placeholder color

瘦欲@ 提交于 2019-11-28 16:26:03

问题


Has anyone any idea or code sample on how can I change the text color of the placeholder text of a UISearchBar?


回答1:


for iOS5+ use the appearance proxy

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



回答2:


Found the answer from 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"];



回答3:


Here is a Solution for 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:


First solution is OK, but if you use multiple UISearchBar, or create a lot of instances it may fail. The one solution that always work for me is to use also appearance proxy but directly on 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];



回答5:


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
}



回答6:


Swift 3

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



回答7:


Try this and see: (I tested below code with 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
    }
}

Here is result:




回答8:


Try this:

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

You can also set this in storyboard, select search bar, add entry under User Defined Runtime Attributes:

_searchField._placeholderLabel.textColor

of type Color and select the color you need.




回答9:


It's an old post but please check this post for an appropriate solution iPhone UITextField - Change placeholder text color




回答10:


It looks like Apple does not want us to play with the placeholder colors when it comes to UISearchBar class. So, let's create our own placeholder label!

  • No subclassing.
  • Works with iOS 13 SDK.
  • Just one innocent workaround.

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



回答11:


After surveyed a couple of answers, I come out this, hope its help

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



回答12:


This solution works on Xcode 8.2.1. with 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
    }
}

Usage example:

searchController.searchBar.setPlaceholderTextColorTo(color: mainColor)



回答13:


iOS 13

Previous solutions may not work on iOS 13 because new searchTextField has been added, and you can set attributed string on it.

I wrapped that into category:

@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



回答14:


This is an old question, but for anyone stumbling on it nowadays, you can change the search icon on iOS 8.x - 10.3 using the following:

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

Regarding the placeholder text color, you may check my other answer, which uses a Category, here: UISearchBar change placeholder color




回答15:


Try this:

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


来源:https://stackoverflow.com/questions/11827585/uisearchbar-change-placeholder-color

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!