直接上代码。
1.初始化
UISearchBar *searchBar = [[UISearchBaralloc]initWithFrame:CGRectMake(0,0, 320,40)];
searchBar.placeholder =@"搜索"; //和textfield一样有placeholder属性
searchBar.delegate =self;
[self.viewaddSubview:searchBar];
//由于个人需求 需要使用圆角的搜索框所以顺便对searchBar进行了一次遍历取出textfiled(ps:如果想修改searchBar背景 可以用imgaeView去接收view)
for (UIView *viewin searchBar.subviews) {
if ([view isKindOfClass:NSClassFromString(@"UIView")] && view.subviews.count > 0) {
_textfield = [view.subviewsobjectAtIndex:1];
_textfield.layer.cornerRadius =14;
_textfield.layer.masksToBounds =YES;
}
}
#pragma mark 输入内容就会触发
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
NSLog(@"1");
}
#pragma mark 点击搜索栏中的textFiled触发
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
_textfield.placeholder =@"输入书名/作者";
//弹出键盘的一瞬间 给背景加了一层灰色蒙版,用于点击回首键盘。
_buttonBackground = [MyButtonmakeButtonFrame:CGRectMake(0,40, 320, 568 -40) withButtonBackGroundColor:[UIColorcolorWithWhite:0.1alpha:0.1]withButtonBackImageName:nilwithButtonTitle:nilwithButtonTitleColor:nilwithButtonTitleFont:nil];
[_buttonBackgroundaddTarget:selfaction:@selector(buttonSearch)forControlEvents:UIControlEventTouchUpInside];
[self.viewaddSubview:_buttonBackground];
}
#pragma mark 点击search跳到搜索结果页
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
CartoonSearchViewController *vc = [[CartoonSearchViewControlleralloc]init];
[self.navigationControllerpushViewController:vc animated:YES];
}
其实还有很多方法,具体的大家可以参考api文档,列出来的只有3个,个人认为最为常用还是第2个,第3个。