废话不多说,直接上代码//写一个背景View,贴在导航控制器上UIView *BJview = [[UIView alloc] initWithFrame:CGRectMake(40, 33, self.view.frame.size.width - 80, 40)];self.navigationItem.titleView = BJview;//创建seachBarself.seachBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, BJview.bounds.size.width, 40)];//去掉seachBar的黑线self.seachBar.backgroundImage = [UIImage new];self.seachBar.delegate = self;self.seachBar.placeholder = @"请输入要搜索的内容";//成为键盘的第一响应者[self.seachBar becomeFirstResponder];[BJview addSubview:self.seachBar];//通过KVC拿到textFieldUITextField *seachTextFild = [self.seachBar valueForKey:@"searchField"];拿到textField之后就可以肆意妄为了//修改字体颜色seachTextFild.textColor = [UIColor redColor];//修改字体大小seachTextFild.font = [UIFont systemFontOfSize:14];//修改光标颜色[seachTextFild setTintColor:[UIColor colorWithRed:35/255.0 green:185/255.0 blue:165/255.0 alpha:1.0]];//更改searchBar 中PlaceHolder 字体颜色[searchField setValue:[UIColor blackColor] forKeyPath:@"_placeholderLabel.textColor"]; self.seachTextFild = seachTextFild;//修改搜索图标UIImageView *img = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"sear"]];img.frame = CGRectMake(10, 0,20,20);self.searchField.leftView = img;self.searchField.leftViewMode = UITextFieldViewModeAlways;//修改clearButtonUIButton *clearButton = [self.searchField valueForKey:@"_clearButton"];[clearButton setImage:[UIImage imageNamed:@"dele.png"] forState:UIControlStateNormal];复制代码
UISearchBar 的代理方法//代理方法 实时监听输入框的文字变动-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{ NSLog(@"%@",searchText);}//searchBar的确定点击事件-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{ NSLog(@"%@",self.seachBar.text);}将要开始编辑时的回调,返回为NO,则不能编辑- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar;已经开始编辑时的回调- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar;将要结束编辑时的回调- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar;已经结束编辑的回调- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar;编辑文字改变前的回调,返回NO则不能加入新的编辑文字-(BOOL)searchBar: (UISearchBar )searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString )text;书本按钮点击的回调- (void)searchBarBookmarkButtonClicked:(UISearchBar *)searchBar;取消按钮点击的回调- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar;搜索结果按钮点击的回调- (void)searchBarResultsListButtonClicked:(UISearchBar *)searchBar;搜索栏的附加试图中切换按钮触发的回调-(void)searchBar:(UISearchBar*)searchBar selectedScopeButtonIndexDidChange:(NSInteger)selectedScope;复制代码