如何在ios8中更改UISearchBar文本字段背景颜色和文本颜色

时间:2015-10-06 11:35:23

标签: objective-c ios8

我使用下面的代码来更改UISearchBar文本字段背景颜色。

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

但它对我不起作用,任何人都可以提供解决方案。  提前谢谢

2 个答案:

答案 0 :(得分:19)

试试这个:

UITextField *searchField = [self.searchBar valueForKey:@"searchField"];

// To change background color
searchField.backgroundColor = [UIColor blueColor];

// To change text color
searchField.textColor = [UIColor redColor];

// To change placeholder text color
searchField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"Some Text"];
UILabel *placeholderLabel = [searchField valueForKey:@"placeholderLabel"];
placeholderLabel.textColor = [UIColor grayColor];

答案 1 :(得分:9)

试试这段代码

[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setBackgroundColor:[UIColor grayColor]];

OR

试试这个

- (void)viewDidLoad
    {
        [super viewDidLoad];

        //change the background color

 [[self searchViewForTextFieldBg:self.searchTextfield] setBackgroundColor:[UIColor grayColor]];

//change the textcolor
self.searchTextfield.textColor =[UIColor greenColor];

    }

    - (UITextField*)searchViewForTextFieldBg:(UIView*)view
{
    if ([view isKindOfClass:[UITextField class]]) {
        return (UITextField*)view;
    }
    UITextField *searchTextField;
    for (UIView *subview in view.subviews) {
        searchTextField = [self searchViewForTextFieldBg:subview];
        if (searchTextField) {
            break;
        }
    }
    return searchTextField;
}