UISearchBar即搜索框对应的bar。
1、创建
UISearchBar * searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 20, 320, 40)];
2、设置属性
searchBar.placeholder = [NSString stringWithFormat:@"请输入搜索关键词"]; //placeholder
// searchBar.prompt = [NSString stringWithFormat:@"搜索框"];
searchBar.barStyle = UIBarStyleDefault; //默认为default
searchBar.tintColor = [UIColor blueColor]; //设置光标的颜色
searchBar.translucent = YES; //设置透明度
[searchBar setBackgroundImage:[UIImage imageNamed:@"default"]]; //设置背景图片
[searchBar setSearchFieldBackgroundImage:[UIImage imageNamed:@"default"] forState:UIControlStateNormal]; //设置搜索框中的背景
// [searchBar setSearchFieldBackgroundPositionAdjustment:UIOffsetMake(5, 5)]; //设置搜索框中文本框的背景的偏移量
[searchBar setSearchResultsButtonSelected:YES];
[searchBar setShowsSearchResultsButton:YES]; //设置是否显示搜索结果的button
// [searchBar setSearchTextPositionAdjustment:UIOffsetMake(10, 10)]; //设置搜索框中文本框的文本偏移量
// searchBar setInputAccessoryView:_btnHide];// 提供一个遮盖视图
[searchBar setKeyboardType:UIKeyboardTypeEmailAddress];// 设置键盘样式
//设置搜索框下面的分栏条
[searchBar setShowsScopeBar:YES];// 是否显示分栏条
[searchBar setScopeButtonTitles:[NSArray arrayWithObjects:@"Singer",@"Song",@"Album", nil]];// 分栏条,栏目
[searchBar setScopeBarBackgroundImage:[UIImage imageNamed:@"image3"]];// 分栏条的背景颜色
[searchBar setSelectedScopeButtonIndex:1];// 分栏条默认选中的按钮的下标
[searchBar setShowsBookmarkButton:YES];// 是否显示右侧的“书图标”
[searchBar setShowsCancelButton:YES];// 是否显示取消按钮
[searchBar setShowsCancelButton:YES animated:YES];
//设置自动修正功能(一般不用)
[searchBar setSpellCheckingType:UITextSpellCheckingTypeYes];// 设置自动检查的类型
[searchBar setAutocorrectionType:UITextAutocorrectionTypeDefault];// 是否提供自动修正功能,一般设置为UITextAutocorrectionTypeDefault
3、实现UISearchBarDelegate
主要有3个方法
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
[searchBar resignFirstResponder]; //键盘收起
}
//点击取消button后执行的操作
- (void)searchBarCancelButtonClicked:(UISearchBar *) searchBar
{
[searchBar resignFirstResponder]; //键盘收起
[searchBar setShowsCancelButton:NO animated:YES];
}
//todo
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
}