自定义的searchBar

注意:UISearchBar设置backgroundColor不起作用,可以直接用backgroundImage

//
//  ViewController.m
#import "ViewController.h"

@interface ViewController ()
    

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UISearchBar *search = [[UISearchBar alloc]initWithFrame:CGRectMake(20, 40, 414-40, 50)];
//    search.showsCancelButton = true;
    search.showsBookmarkButton = true;
    search.backgroundImage = [UIImage imageNamed:@"bg.jpeg"];
    search.layer.cornerRadius = 5.0;
    search.placeholder = @"搜索";
    search.delegate = self;
    [self.view addSubview:search];
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    searchBar.showsCancelButton = true;
    //找到取消按钮    
    UIButton *cancelButton = [searchBar valueForKey:@"cancelButton"];
    
    //修改标题和标题颜色
    [cancelButton setTitle:@"取消" forState:UIControlStateNormal];
    [cancelButton setTitleColor:[UIColor greenColor] forState:UIControlStateNormal];
//    [self.view addSubview:searchBarx];
    
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    searchBar.showsCancelButton = false;
    searchBar.text = nil;
    [searchBar resignFirstResponder];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end

你可能感兴趣的:(自定义的searchBar)