ios7以上修改UISearchBar的字体,背景颜色(内外框)

本人在工作之余需要使用UISearchBar,发现看似一个小小的搜索框其实还是有很多麻烦之处,尤其是在ios7以后,自己在网上找了很多但很多都不行或者没有用,今天在此小总结一下搜索框的用法。
  • 添加两个数组,一个UISearchController
@property(nonatomic,retain)UISearchController *searchController;
@property(nonatomic,retain)NSMutableArray *searchResults;//接收数据源结果
@property(nonatomic,retain)NSArray * dibiaoArr;//原始数据
  • 创建UISearchBar(添加代理UISearchBarDelegate)
 //搜索框
    self.searchController = [[UISearchController alloc]initWithSearchResultsController:nil];
    _searchController.searchBar.frame = CGRectMake(10, 10, screen_width-20, 40);
    self.searchController.dimsBackgroundDuringPresentation = false;
    _searchController.searchBar.delegate = self;
    //按钮字体颜色
    _searchController.searchBar.tintColor = RGBColor(183, 142, 68, 1.0);
    //改变搜索框外部框的颜色(需要隐藏background才能显示背景色)
    _searchController.searchBar.backgroundImage = [self imageWithColor:[UIColor clearColor] size:_searchController.searchBar.bounds.size];
    //水印
    _searchController.searchBar.placeholder = @"请输入地址";
    [_searchController.searchBar sizeToFit];
    self.searchController.searchResultsUpdater = self;
    //用textfiled代替搜索框
    UITextField *searchField=[_searchController.searchBar valueForKey:@"_searchField"];
    searchField.backgroundColor = RGBColor(40, 39, 44, 1.0);
    //水印颜色
    [searchField setValue:RGBColor(137, 136, 140, 1.0) forKeyPath:@"_placeholderLabel.textColor"];
    //搜索栏表头视图
    self.tableView.tableHeaderView = _searchController.searchBar;
    
    self.dibiaoArr = @[@"下想",@"查快递"];
  • 效果如图
ios7以上修改UISearchBar的字体,背景颜色(内外框)_第1张图片
50FBB2CA-6137-44FA-ABAC-1A096B5EFAB7.png
这里很多人在修改搜索框的外框背景颜色,用了backgroundColor 但是没什么反应,通过debug可以看到这里多了一层view,然后将设置的颜色遮盖掉了。内部框的属性直接修改textfiled就可以了,外部框需要注意.
  • 以为这样设置就可以了,结果点击编辑搜索框的背景颜色又改变了。这时候需要去代理方法:-(void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar添加属性。
     searchBar.barTintColor = RGBColor(40, 39, 44, 1.0);
    // 修改UISearchBar右侧的取消按钮文字颜色及背景图片
        for (id searchbuttons in [[_searchController.searchBar subviews][0]subviews]) //只需在此处修改即可
            if ([searchbuttons isKindOfClass:[UIButton class]] ) {
             [cancelButton setTitle:@"取消"forState:UIControlStateNormal];
                [cancelButton setTitle:@"取消"forState:UIControlStateSelected];
                 [cancelButton setTitleColor:RGBColor(183, 142, 68, 1.0) forState:UIControlStateNormal];
                [cancelButton setTitleColor:RGBColor(183, 142, 68, 1.0) forState:UIControlStateHighlighted];
                
            }


  • 然而到这里,发现还是有问题,就是第一次进入编辑时,取消按钮的字体没有改变,再进入第二次的时候却改变了,说明当第一次进入编辑状态时,取消按钮根本还没有被加载,在这里我使用的是延迟1秒后再进行查找,等按钮加载出来后再执行方法。这样就没问题了。
  • 效果如图
ios7以上修改UISearchBar的字体,背景颜色(内外框)_第2张图片
86195412-8385-40F0-B2E7-990DFB7A3515.png

关于tableview和searchbar的代理方法我就不多说了,主要就是这几个点注意就好了。

你可能感兴趣的:(ios7以上修改UISearchBar的字体,背景颜色(内外框))