1. 程式人生 > >自定義UISearchBar背景、邊框、左側圖示、刪除圖示、取消按鈕

自定義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];
        }
    }
    
}