我无法使其与上述任何解决方案一起正常工作。
我创建了以下 UISearchBar 类别,它可以在 iOS 8.4 和 10.3 上正常工作:
UISearchBar+PlaceholderColor.h
#import <UIKit/UIKit.h>
@interface UISearchBar (PlaceholderColor)
- (void)setPlaceholderColor:(UIColor *)placeholderColor;
@end
UISearchBar+PlaceholderColor.m
#import "UISearchBar+PlaceholderColor.h"
@implementation UISearchBar (PlaceholderColor)
- (void)setPlaceholderColor:(UIColor *)placeholderColor {
UILabel *labelView = [self searchBarTextFieldLabelFromView:self];
[labelView setTextColor:placeholderColor];
}
- (UILabel *)searchBarTextFieldLabelFromView:(UIView *)view {
for (UIView *v in [view subviews]) {
if ([v isKindOfClass:[UILabel class]]) {
return (UILabel *)v;
}
UIView *labelView = [self searchBarTextFieldLabelFromView:v];
if (labelView) {
return (UILabel *)labelView;
}
}
return nil;
}
@end
用法:
[mySearchBar setPlaceholderColor:[UIColor redColor]];
重要提示:
确保调用 setPlaceholderColor:AFTER 您的 UISearchBar 已添加到视图并创建了其视图层次结构。
如果您以编程方式打开搜索栏,请将其称为 AFTER 您的 becomeFirstResponder 调用,如下所示:
[mySearchBar becomeFirstResponder];
[searchBar setPlaceholderColor:[UIColor redColor]];
否则,如果您使用 UISearchBarDelegate:
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
[searchBar setPlaceholderColor:[UIColor redColor]];
}