searchBar建立在view上的问题
要先创建一个底部view, 然后将searchBar添加到该view上面
//除去在搜索框后面的灰色背景
[_searchBar.subviews[0].subviews[0] removeFromSuperview];
[_searchBackView addSubview:_searchBar];
更改searchBar内部textField的尺寸
新建一个类继承UISearchBar, 重写layoutSubviews,
要区分两种情景, 即是否需要右侧有个取消按钮.
如果不需要, 则直接让textField尺寸和外部设置的searchBar尺寸一致即可;
如果需要, 则外部传进来的宽度, 原点坐标和高度随searchBar尺寸即可
- (void)layoutSubviews{
[super layoutSubviews];
// view是searchBar中的唯一的直接子控件
for (UIView *view in self.subviews) {
for (UIView *subView in view.subviews) {
if ([subView isKindOfClass:[UITextField class]]) {
UITextField *t = (UITextField *)subView;
if (!self.showsCancelButton) {
t.frame = self.bounds;
}
else{
CGFloat height = self.bounds.size.height;
t.frame = CGRectMake(self.bounds.origin.x, self.bounds.origin.y, _width, height);
}
}
}
}
}
修改右侧取消按钮字体颜色大小等参数
记得_searchBar.showsCancelButton = YES;
UIView *topView = _searchBar.subviews[0];
for(UIView *subView in topView.subviews) {
if([subView isKindOfClass:NSClassFromString(@"UINavigationButton")]) {
UIButton *cancelButton = (UIButton *)subView;
cancelButton.titleLabel.font = [UIFont systemFontOfSize:15 * SCALE_WIDTH];
[cancelButton setTitleColor:THEME_COLOR forState:UIControlStateNormal];
cancelButton.enabled = YES;//UISearchBar失去焦点时, 取消按钮enable为NO
break;
}
}
修改searchBar里面textField的背景颜色(默认是白色)
UIView *searchTextField = nil;
_searchBar.barTintColor = [UIColor whiteColor];
searchTextField = [[[_searchBar.subviews firstObject] subviews] lastObject];
searchTextField.backgroundColor = kRGBColor(239, 239, 243);
修改searchBar里面textField的圆角
UITextField *searchField = [_searchBar valueForKey:@"searchField"];
if (searchField) {
searchField.layer.cornerRadius = 10.0f;
}
取消按钮中英文切换
在Project中info,在Localizations默认只有English这一项, 我们只需在Localizations上添加Chinese就可以了, 你还可以根据你的需要添加其他的语言.
如果用户把手机语言设成英文, 那么显示的就是英文, 设置成中文,那么显示的就是中文.
感谢 http://blog.sina.com.cn/s/blog_7f6480790101fvlk.html
在serachBar内部右侧增加扫描按钮
先写个按钮的懒加载
#pragma mark 扫描按钮懒加载
- (NABaseButton *)btnOfScan{
if (!_btnOfScan) {
CGFloat myWidth = 16.0f;
CGFloat myHeight = 16.0f;
_btnOfScan = [NABaseButton buttonWithType:UIButtonTypeCustom];
_btnOfScan.frame = CGRectMake(0.0f, 0.0f, myWidth, myHeight);
[_btnOfScan setImage:[UIImage imageNamed:@"searchBarScan"] forState:UIControlStateNormal];
[_btnOfScan addTarget:self action:@selector(clickSearchBarRightView:) forControlEvents:UIControlEventTouchUpInside];
}
return _btnOfScan;
}
在视图已经出现的时候
#pragma mark - 视图已经出现
- (void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
for(UIView *subView in _searchController.searchBar.subviews.firstObject.subviews) {
if([subView isKindOfClass: [UITextField class]]){
UITextField *searchField = (UITextField *)subView;
searchField.rightView = self.btnOfScan;
searchField.rightViewMode = UITextFieldViewModeAlways;
searchField.clearButtonMode = UITextFieldViewModeNever;
}
}
}