self.searchBar.resignFirstResponder()
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+0.1) {
(self.searchBar.value(forKey: "cancelButton") as! UIButton).isEnabled = true
}
```
From: <http:
在日常工作中对于UISearchBar的操作主要集中在:
* 设置UISearchBar中textfiled的边框及圆角
* 设置占位文字的大小及颜色
* 设置输入文字的大小及颜色
* 修改搜索图标
* 修改取消按钮的文本
* ....
实现的方式有很多,就设置边框而言:可以设置背景图片实现效果;或者直接用UITextField来代替UISearchBar等等。但是以上的操作主要是集中在UISearchBar内部的UITextField上,因此获取到UISearchBar内部的UITextField便可以实现以上的效果:
* 通过KVC获取子视图
UISearchBar *searchBar = [[UISearchBar alloc]init];
UITextField *searchField = [searchBar valueForKey:@"_searchField"];
UIView *backgroundView = [searchBar valueForKey:@"_background"];
UIButton *cancelButton = [searchBar valueForKey:@"_cancelButton"];
* 改变输入框文本
UITextField *searchField = [searchBar valueForKey:@"_searchField"];
searchField.font = font(12);
searchField.textColor = UIColorRgb(32,32,32);
[searchField setValue:UIColorRgb(197,197,197) forKeyPath:@"_placeholderLabel.textColor"];
* 设置输入框边框及圆角
UITextField *searchField = [searchBar valueForKey:@"_searchField"];
searchField.layer.cornerRadius = 4.0f;
searchField.layer.masksToBounds = YES;
searchField.layer.borderWidth = 0.5f;
searchField.layer.borderColor = UIColorRgbAlpha(95,96,108,0.2).CGColor;
* 设置输入框内搜索图标
UITextField *searchField = [searchBar valueForKey:@"_searchField"];
UIImage *image = [UIImage imageNamed:@"search"];
UIImageView *iView = [[UIImageView alloc] initWithImage:image];
iView.frame = CGRectMake(0, 0, 15, 15);
searchField.leftView = iView;
* 改变取消按钮的title
UIButton*cancelButton = [searchBar valueForKey:@"_cancelButton"];
[cancelButton setTitle:@"Close"forState:UIControlStateNormal];
---
KVC或者textField的clear属性
```
UIButton *button = [textField valueForKey:@"_clearButton"];
[button setImage:[UIImage imageNamed:@"icon_blueclear"] forState:UIControlStateNormal];
field.clearButtonMode = UITextFieldViewModeWhileEditing;
let clearBtn = self.textField.value(forKey: "_clearButton") as! UIButton
clearBtn.setImage(UIImage(named:"sy-ss"), for: UIControlState.normal)
clearBtn.setImage(UIImage(named:"sy-ss"), for: UIControlState.highlighted)