一.初始化:UISearchBar继承于UIView,我们可以像创建View那样创建searchBar
UISearchBar * bar = [[UISearchBar alloc]initWithFrame:CGRectMake(20, 100, 250, 40)];
[self.view addSubview:bar];
二.属性
@property(nonatomic) UIBarStyle barStyle;
这个属性可以设置searchBar的搜索框的风格,枚举如下:
typedef NS_ENUM(NSInteger, UIBarStyle) {
UIBarStyleDefault = 0,//默认风格 白色搜索框,多出的背景为灰色
UIBarStyleBlack = 1,//黑色风格,黑色的搜索框
//下面两个枚举已经被禁用,作用和黑色风格一样
UIBarStyleBlackOpaque = 1, // Deprecated. Use UIBarStyleBlack
UIBarStyleBlackTranslucent = 2, // Deprecated. Use UIBarStyleBlack and set the translucent property to YES
};
示例:
1.UIBarStyleDefault
注释: 默认风格;灰色背景,白色文字
2.UIBarStyleBlack
注释:纯黑色背景,白色文字
3.UIBarStyleBlackOpaque
注释:纯黑色背景,白色文字
4.UIBarStyleBlackTranslucent
注释:透明黑色背景,白色文字
@property(nonatomic,copy) NSString *text;
注释: 设置搜索框中的文字
@property(nonatomic,copy) NSString *prompt;
注释:这个属性的官方解释是在搜索框顶部显示一行文字,其实就是背景文字,上图说明:
bar.prompt = @"搜索框";
[email protected]"测试"
效果如下:
@property(nonatomic,copy) NSString *placeholder;
注释:和其他文本输入控件的placeholder相同,在输入文字时就会消失
效果图:
@property(nonatomic) BOOL showsBookmarkButton;
注释:是否在搜索框右侧显示一个图书的按钮,默认为NO,YES的效果如下:
@property(nonatomic) BOOL showsCancelButton;
注释: 是否显示取消按钮,默认为NO,YES的效果如下:
@property(nonatomic) BOOL showsSearchResultsButton;
注释:是否显示搜索结果按钮,默认为NO,YES效果如下:
@property(nonatomic, getter=isSearchResultsButtonSelected) BOOL searchResultsButtonSelected ;
注释:设置搜索结果按钮的选中状态
- (void)setShowsCancelButton:(BOOL)showsCancelButton animated:(BOOL)animated;
设置显示取消按钮
@property(nonatomic,retain) UIColor *tintColor;
注释:设置这个颜色值会影响搜索框中的光标的颜色,当设置此属性时,barStyle将失效;
@property(nonatomic,retain) UIColor *barTintColor;
注释:设置这个颜色会影响搜索框的背景颜色
@property (nonatomic) UISearchBarStyle searchBarStyle;
注释:设置搜索框整体的风格,枚举如下:
typedef NS_ENUM(NSUInteger, UISearchBarStyle) {
UISearchBarStyleDefault, // currently UISearchBarStyleProminent
UISearchBarStyleProminent, // 显示背景
UISearchBarStyleMinimal // 不显示背景
} NS_ENUM_AVAILABLE_IOS(7_0);
示例:
1>UISearchBarStyleDefault
2>UISearchBarStyleProminent
3>UISearchBarStyleMinimal
@property(nonatomic,assign,getter=isTranslucent) BOOL translucent;
注释:设置是否半透明
@property(nonatomic) BOOL showsScopeBar ;
searchBar.showsScopeBar = YES; searchBar.scopeButtonTitles = @[@"你",@"我",@"他"];
注释:是否显示搜索栏的附件选择按钮试图,要想显示这个试图,首先要将这个属性设置为YES,之后给按钮数组中添加按钮,使用下面这个属性:
@property(nonatomic,copy) NSArray *scopeButtonTitles ;
注释:设置选择按钮试图的按钮标题
@property(nonatomic) NSInteger selectedScopeButtonIndex;
注释:设置一个默认的选中按钮
@property (nonatomic, readwrite, retain) UIView *inputAccessoryView;
注释:键盘的附属试图
小技巧:如果要设置这个属性,那么,就最好定义一个UIButton控件,这样,当点击该遮盖层的话,可以利用按钮事件,
设置:[self.searchBar resignFirstResponder];让搜索框放弃第一焦点。(iPhone电话薄也是这么做的,感觉很人性化)。
@property(nonatomic,retain) UIImage *backgroundImage;
注释:设置搜索框的背景图案
@property(nonatomic,retain) UIImage *scopeBarBackgroundImage;
注释:
1>设置附属选择按钮视图的背景图案
2>这一对方法可以设置和获取某个状态枚举下的搜索框的背景图案
- (void)setBackgroundImage:(UIImage *)backgroundImage forBarPosition:(UIBarPosition)barPosition barMetrics:(UIBarMetrics)barMetrics ;
- (UIImage *)backgroundImageForBarPosition:(UIBarPosition)barPosition barMetrics:(UIBarMetrics)barMetrics
3>这一对方法用于设置和获取搜索框中TextField的背景图案
- (void)setSearchFieldBackgroundImage:(UIImage *)backgroundImage forState:(UIControlState)state;
- (UIImage *)searchFieldBackgroundImageForState:(UIControlState)state;
4>这一对方法用于获取和设置搜索栏icon图片的图案
- (void)setImage:(UIImage *)iconImage forSearchBarIcon:(UISearchBarIcon)icon state:(UIControlState)state ;
- (UIImage *)imageForSearchBarIcon:(UISearchBarIcon)icon state:(UIControlState)state ;
5>这一对方法用于设置和获取搜索框的附加选择按钮视图的背景图案
- (void)setScopeBarButtonBackgroundImage:(UIImage *)backgroundImage forState:(UIControlState)state;
- (UIImage *)scopeBarButtonBackgroundImageForState:(UIControlState)state;
6>这一对方法用于获取和设置附加选择按钮视图中切换按钮的图案
- (void)setScopeBarButtonDividerImage:(UIImage *)dividerImage forLeftSegmentState:(UIControlState)leftState rightSegmentState:(UIControlState)rightState;
- (UIImage *)scopeBarButtonDividerImageForLeftSegmentState:(UIControlState)leftState rightSegmentState:(UIControlState)rightState;
7>这一对方法用于设置和获取切换按钮标题文字的字体属性字典
- (void)setScopeBarButtonTitleTextAttributes:(NSDictionary *)attributes forState:(UIControlState)state;
- (NSDictionary *)scopeBarButtonTitleTextAttributesForState:(UIControlState)state;
@property(nonatomic) UIOffset searchFieldBackgroundPositionAdjustment;
searchBar.placeholder = @"搜索框"; searchBar.searchFieldBackgroundPositionAdjustment =UIOffsetMake(20, 0) ;
注释:textfield在搜索框中的位置偏移
@property(nonatomic) UIOffset searchTextPositionAdjustment;
searchBar.placeholder = @"搜索框"; searchBar.searchTextPositionAdjustment =UIOffsetMake(20, 0) ;
注释:
1>搜索文字在搜索框中的位置偏移
2>设置搜索栏中图片的位置偏移:
- (void)setPositionAdjustment:(UIOffset)adjustment forSearchBarIcon:(UISearchBarIcon)icon;
- (UIOffset)positionAdjustmentForSearchBarIcon:(UISearchBarIcon)icon;
图片的枚举如下
typedef NS_ENUM(NSInteger, UISearchBarIcon) {
UISearchBarIconSearch, //搜索图标
UISearchBarIconClear, // 清除图标
UISearchBarIconBookmark, // 书本图标
UISearchBarIconResultsList, // 结果列表图标
};
@property(nonatomic) UIOffset searchFieldBackgroundPositionAdjustment
三,代理方法:
1>- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar;
注释:将要开始编辑时的回调,返回为NO,则不能编辑
示例:
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{ [self.searchBar setShowsCancelButton:YES animated:YES]; [self.navigationController setNavigationBarHidden:YES animated:YES]; [self controlAccessoryView:0.9];// 显示遮盖层。 return YES; }
2>- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar;
注释:已经开始编辑时的回调
3>- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar;
注释:将要结束编辑时的回调
3>- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar;
注释:已经结束编辑的回调
4>- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText;
注释:编辑文字改变的回调
示例:// 当搜索内容变化时,执行该方法。很有用,可以实现时实搜索
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText;{ NSLog(@"textDidChange---%@",searchBar.text); [liveViewAreaTable searchDataBySearchString:searchBar.text];// 搜索tableView数据 [self controlAccessoryView:0];// 隐藏遮盖层。 }
5>- (BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text ;
注释:编辑文字改变前的回调,返回NO则不能加入新的编辑文字
6>- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar;
注释:搜索按钮点击的回调
示例:
[self.searchBar resignFirstResponder];// 放弃第一响应者 [liveViewAreaTable searchDataBySearchString:searchBar.text]; [self.navigationController setNavigationBarHidden:NO animated:YES]; [self controlAccessoryView:0];// 隐藏遮盖层。
7>- (void)searchBarBookmarkButtonClicked:(UISearchBar *)searchBar;
注释:书本按钮点击的回调
8>- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar;
注释:取消按钮点击的回调
示例:
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{ [self.searchBar resignFirstResponder]; [self.searchBar setShowsCancelButton:NO animated:YES]; [liveViewAreaTable searchDataBySearchString:nil];// 搜索tableView数据 [self.navigationController setNavigationBarHidden:NO animated:YES]; [self controlAccessoryView:0];// 隐藏遮盖层。 }
9>- (void)searchBarResultsListButtonClicked:(UISearchBar *)searchBar;
注释:搜索结果按钮点击的回调
10>- (void)searchBar:(UISearchBar *)searchBar selectedScopeButtonIndexDidChange:(NSInteger)selectedScope;
注释:搜索栏的附加试图中切换按钮触发的回调
四.UISearchBar 的自定义
1>设置背景色
默认状态
//设置背景图是为了去掉上下黑线 self.customSearchBar.backgroundImage = [[UIImage alloc] init]; // 设置SearchBar的颜色主题为白色 self.customSearchBar.barTintColor = [UIColor whiteColor]
自定义状态
2>设置边框颜色和圆角
UITextField *searchField = [self.customSearchBar valueForKey:@"searchField"]; if (searchField) { [searchField setBackgroundColor:[UIColor whiteColor]]; searchField.layer.cornerRadius = 14.0f; searchField.layer.borderColor = [UIColor colorWithRed:247/255.0 green:75/255.0 blue:31/255.0 alpha:1].CGColor; searchField.layer.borderWidth = 1; searchField.layer.masksToBounds = YES; }
这段代码有个特别的地方就是通过KVC获得到UISearchBar的私有变量
searchField(类型为UITextField),设置SearchBar的边框颜色和圆角实际上也就变成了设置searchField的边框颜色和圆角,你可以试试直接设置SearchBar.layer.borderColor和cornerRadius,会发现这样做是有问题的。
3>设置按钮(取消按钮)
注意:需要特别注意的是设置searchBar的tintColor会使输入框的光标颜色改变,可以通过设置searchField的tintColor来修正。
1)利用系统的运行时(Runtime)机制设置:
UIButton *btn = [[UIButton alloc] init];
btn.titleLabel.textAlignment = NSTextAlignmentCenter;
[btn setTitle:@"123" forState:UIControlStateNormal];
[btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
[searchBar setValue:btn forKeyPath:@"cancelButton"];
运行结果:达不到需求,需要调整按钮和搜索框的位置;
2)遍历UISearchBar的子控件,设置里面的button;
<span style="font-size:12px;">[searchBar setShowsCancelButton:YES animated:YES]; </span>
<span style="font-size:12px;">for ( id searchView in [[[searchBar subviews] lastObject]subviews]) { if ([[searchView class] isSubclassOfClass: NSClassFromString(@"UINavigationButton")]) { UIButton *cancelBtn = (UIButton *)searchView; [cancelBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal]; [cancelBtn setTitle:nil forState:UIControlStateNormal]; [cancelBtn setBackgroundImage:[UIImage imageNamed:@"AppIcon29x29"] forState:UIControlStateNormal]; } }</span>
该方法如果设置title,设置titleColor与BackgroundImage将失效;字体的颜色将显示为系统的默认颜色;
所以该方法只适合设置按钮的颜色和背景图片;文字只能显示cancel或者取消;
可以将项目配置设置为支持中文,字体将显示为取消;
项目配置方法
项目配置方法
注意点:
显示cancel按钮的方法要写在自定义按钮方法前面
3)利用appearance 设置:
该方法不仅可以设置文字、颜色,还可以设置字体大小;
NSMutableDictionary *attr = [NSMutableDictionary dictionary]; attr[NSFontAttributeName] = [UIFont systemFontOfSize:13]; attr[NSForegroundColorAttributeName] = [UIColor redColor]; [[UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class] , nil] setTitle:@"N"]; [[UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class], nil] setTitleTextAttributes:attr forState:UIControlStateNormal];
运行结果:
注意点:
补充:
方法2与方法3基本可以满足需求;
若修改太多,可以Textfile与button自定义一个搜索框;
而且方法2与3可以结合使用:
4>设置输入框的颜色和字体
[self.customSearchBar fm_setTextColor:[UIColor blackColor]]; [self.customSearchBar fm_setTextFont:[UIFont systemFontOfSize:14]];
//下面两个方法是UISearchBar分类代码
- (void)fm_setTextColor:(UIColor *)textColor { if (IS_IOS9) { [UITextField appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]].textColor = textColor; }else { [[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setTextColor:textColor]; } }
- (void)fm_setCancelButtonTitle:(NSString *)title { if (IS_IOS9) { [[UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]] setTitle:title]; }else { [[UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class], nil] setTitle:title]; } }
5>设置搜索图标
[self.customSearchBar setImage:[UIImage imageNamed:@"Search_Icon"] forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];
为了跟系统默认Icon的有个明显的对比,我特殊找了张绿色的搜索Icon,效果见下图:
设置搜索Icon.png
建议: 还可以设置其他的Icon(如清除按钮图标),也是用上面的方法,具体要设置什么,可以去看看UISearchBarIcon这个枚举。
参考:这里