UISearchBar字体颜色等修改

修改系统自带的控件最和谐的方式当然属:Category了

接下来创建Category来修改UISearchBar字体颜色等
//.h
#import 

@interface UISearchBar (JING)
//每个searchBar获取textfiled 尽量  调用一次  有循环
- (UITextField *)searchBarTextFiled;
@end

//.m
- (UITextField *)searchBarTextFiled{
    for (UIView* subview in [[self.subviews lastObject] subviews]) {
        if ([subview isKindOfClass:[UITextField class]]) {
            return (UITextField *)subview;
        }else if ([subview isKindOfClass:NSClassFromString(@"UISearchBarBackground")]){
            [subview removeFromSuperview];
        }
    }
    return nil;
}
#import "UISearchBar+JING.h"别忘导头文件

核心思想就是通过遍历subview来寻找UITextField

来,看一下是如何使用的

//controller

@property (nonatomic,strong) UISearchBar *searchBar;

//get
-(UISearchBar *)searchBar{
    if (!_searchBar) {
        _searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 200, 44)];
        _searchBar.placeholder = @"昵称/手机号";
        _searchBar.searchBarStyle = UISearchBarStyleMinimal;
        //    _searchBar.returnKeyType = UIReturnKeyDone;
        _searchBar.delegate = self;
        //拿到了textfile
//        UITextField *textfile = _searchBar.searchBarTextFiled;//你也可以这样调用
        UITextField *textfile = [_searchBar searchBarTextFiled];
        textfile.backgroundColor = Listener_Cell_SectionViewGray;//背景色
        textfile.textColor = [UIColor whiteColor];//字体色
//修改placeholder的颜色(通过kvo)
       [textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];   
    }
    return _searchBar;
}

OK大功告成,谢谢~~

你可能感兴趣的:(UISearchBar字体颜色等修改)