#pragma mark - UISearchBarDelegate
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
searchBar.showsCancelButton = YES;
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:setRGBColor(41, 124, 240) forState:UIControlStateNormal];
[cancelBtn setTitleColor:setRGBColor(41, 124, 240) forState:UIControlStateHighlighted];
}
}
}
或者使用KVC的方式:
searchBar.showsCancelButton = YES;
UIButton *cancelBtn = [searchBar valueForKey:@"_cancelButton"];
[cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
[cancelBtn setTitleColor:setRGBColor(41, 124, 240) forState:UIControlStateNormal];
[cancelBtn setTitleColor:setRGBColor(41, 124, 240) forState:UIControlStateHighlighted];
必须在UISearchBar代理方法中设置才生效,可能是因为此时searchBar的opaque属性才被设置为NO。