TextField文本搜索栏中的颜色更改

时间:2017-05-29 07:09:43

标签: ios colors uisearchbar

请检查我的下面的代码,我使用一个navigationbar searchbarsearchbar有一个文本字段,现在我要更改textfield的文字颜色我做了一个下面的代码,但它没有工作,所以请帮助纠正它。

[[UISearchBar appearanceWhenContainedInInstancesOfClasses:@[[UINavigationBar class]]]setTintColor:[UIColor whiteColor]];
[[UITextField appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]]setTextColor:[UIColor whiteColor]];

2 个答案:

答案 0 :(得分:0)

如果您使用的是本机UISearchbar控件,则可以使用下面的代码更改文本颜色

[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setDefaultTextAttributes:@{NSForegroundColorAttributeName:[UIColor redColor]}];

或者您可以通过Identity Inspector为特定的searchBar执行此操作: enter image description here

答案 1 :(得分:0)

试试这个,

NSArray *searchBarSubViews = [[self.searchBar.subviews objectAtIndex:0] subviews];

for (UIView *view in searchBarSubViews) {
    if([view isKindOfClass:[UITextField class]])
    {
        UITextField *txt = (UITextField*)view;
        UIImageView *imgView = (UIImageView*)textField.leftView;
        imgView.image = [imgView.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
        imgView.tintColor = [UIColor whiteColor];

        txt.backgroundColor = [UIColor blackColor];
        txt.textColor = [UIColor RedColor];
        UIButton *btnClear = (UIButton*)[textField valueForKey:@"clearButton"];
        [btnClear setImage:[btnClear.imageView.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forState:UIControlStateNormal];
        btnClear.tintColor = [UIColor whiteColor];
    }
}