iOS Blog

如何设置UISearchBar的title和颜色:

2015-11-25  本文已影响1535人  starfox寒流
#pragma mark - UISearchBarDelegate
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
    NSLog(@"start!");
    searchBar.showsCancelButton = YES;
    NSLog(@"%@",self.searchController.searchBar.subviews[0].subviews);
    for (UIView *view in self.searchController.searchBar.subviews[0].subviews) {
        if ([view isKindOfClass:[UIButton class]]) {
            UIButton *cancelBtn = (UIButton *)view;
            [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
         [cancelBtn setTitleColor:APP_GLOBAL_BUTTON_COLOR forState:UIControlStateNormal];
        }
    }
}

或者使用KVC的方式:

    searchBar.showsCancelButton = YES;
    
    UIButton *cancelBtn = [searchBar valueForKey:@"_cancelButton"];
    [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    [cancelBtn setTitleColor:APP_GLOBAL_BUTTON_COLOR forState:UIControlStateNormal];

必须在UISearchBar代理方法中设置才生效,可能是因为此时searchBar的opaque属性才被设置为NO。
这是在viewDidLoad中初始化searchController时的searchBar:

**2015-11-25 21:26:53.256 wjhg[56555:1674774] ****网络变化通知:****2**
**(lldb) ****po self.searchController.searchBar**
<UISearchBar: 0x7ff553c652a0; frame = (0 0; 375 44); text = ''; gestureRecognizers = <NSArray: 0x7ff553c5e3e0>; layer = <CALayer: 0x7ff553c5c430>>

这是在searchBarTextDidBeginEditing方法中po的searchBar,对比发现多了一个opaque属性,该属性意为不透明。

**2015-11-25 21:27:09.415 wjhg[56555:1674774] start!**
**(lldb) ****po self.searchController.searchBar**
<UISearchBar: 0x7ff553c652a0; frame = (55 0; 265 44); text = ''; opaque = NO; gestureRecognizers = <NSArray: 0x7ff553c5e3e0>; layer = <CALayer: 0x7ff553c5c430>>
上一篇下一篇

猜你喜欢

热点阅读