自定义UISearchBar背景、边框、左侧图标、删除图标、取消按钮

<span style="background-color: rgb(255, 255, 255); font-family: Arial, Helvetica, sans-serif;">自定义UISearchBar背景、边框、左侧图标、删除图标</span>
 self.searchBar = [[UISearchBar alloc] initWithFrame:[AdapterRect adapterRectByWidth:(CGRect){0, 0, 200, 30}]];
    self.searchBar.placeholder = @"搜索商品分类 品牌";
    self.searchBar.delegate = self;
    UIView *searchTextField = nil;
    if ([[[UIDevice currentDevice] systemVersion] doubleValue] >= 7.0) {
        self.searchBar.barTintColor = [UIColor colorFromHexString:@"#27dcfb"];
        searchTextField = [self.searchBar valueForKey:@"_searchField"];
    }else{
        for (UIView *subView in self.searchBar.subviews) {
            if ([subView isKindOfClass:NSClassFromString(@"UISearchBarTextField")]) {
                searchTextField = subView;
                break;
            }
        }
    }
    if (searchTextField) {
        searchTextField.backgroundColor = [UIColor colorFromHexString:@"#27dcfb"];
        searchTextField.layer.masksToBounds = YES;
        searchTextField.layer.cornerRadius = 3.0f;
        searchTextField.layer.borderColor = [UIColor whiteColor].CGColor;
        searchTextField.layer.borderWidth = 0.5;
        ((UITextField *)searchTextField).textColor = [UIColor whiteColor];
        [((UITextField *)searchTextField) setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
    }
    [self.searchBar setImage:[UIImage imageNamed:@"search"] forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];
    [self.searchBar setImage:[UIImage imageNamed:@"cha"] forSearchBarIcon:UISearchBarIconClear state:UIControlStateNormal];
    self.navigationItem.titleView = self.searchBar;


修改UISearchBar的取消按钮上的文字:

- (void)searchBarTitleDidChangedForSearchCancelBtn{
    
    UIButton *cancelButton;
    if (IOS_IS_AT_LEAST_7) {
        UIView *topView = self.searchBar.subviews[0];
        for (UIView *subView in topView.subviews) {
            if ([subView isKindOfClass:NSClassFromString(@"UINavigationButton")]) {
                cancelButton = (UIButton *)subView;
                break;
            }
        }
    }else{
        for(id subView in [self.searchBar subviews]){
            if([subView isKindOfClass:[UIButton class]]){
                cancelButton = (UIButton *)subView;
                break;
            }
        }
    }
    if (cancelButton) {
        if (isSearch) {
            [cancelButton setTitle:@"搜索" forState:UIControlStateNormal];
        }else{
            [cancelButton setTitle:@"取消" forState:UIControlStateNormal];
        }
    }
    
}


展开阅读全文

没有更多推荐了,返回首页