前段时间做了一个UISearchBar相关的需求,今天也总结以下。
1、UISearchBar自定义背景、取消按钮中文设置
- UISearchBar *seachBar=[[UISearchBar alloc] init];
- //修改搜索框背景
- seachBar.backgroundColor=[UIColor clearColor];
- //去掉搜索框背景
- [[searchbar.subviews objectAtIndex:0]removeFromSuperview];
- for (UIView *subview in seachBar.subviews)
- {
- if ([subview isKindOfClass:NSClassFromString(@"UISearchBarBackground")])
- {
- [subview removeFromSuperview];
- break;
- }
- }
- //自定义背景
- UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"40-di.png"]];
- [searchBar insertSubview:imageView atIndex:1];
- //输入搜索文字时隐藏搜索按钮,清空时显示
- - (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
- searchBar.showsScopeBar = YES;
- [searchBar sizeToFit];
- [searchBar setShowsCancelButton:YES animated:YES];
- return YES;
- }
- - (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar {
- searchBar.showsScopeBar = NO;
- [searchBar sizeToFit];
- [searchBar setShowsCancelButton:NO animated:YES];
- return YES;
- }
- //修改UISearchBar取消按钮中文字体
- for (id aa in [searchBar subviews]) {
- if ([aa isKindOfClass:[UIButton class]]) {
- UIButton *btn = (UIButton *)aa;
- [btn setTitle:@"取消" forState:UIControlStateNormal];
- }
- }
2、UISearchBar 的delegate方法
- #pragma mark 搜索控件
- //键盘搜索按钮被点击时触发
- - (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
- UIStoryboard *mainStory = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
- FirstViewController *fVC = [mainStory instantiateViewControllerWithIdentifier:@"goFirstView"];
- fVC.showStr = self.searchBar.text;
- [self presentModalViewController:fVC animated:YES];
- }
- //搜索框输入内容改变时触发
- - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
- }
- //焦点进入搜索框时触发
- - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
- self.soundBtn.hidden = YES;
- [self searchBar:searchBar activate:YES];
- }
- //取消搜索按钮点击时触发
- - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
- self.searchBar.text = @"";
- self.soundBtn.hidden = NO;
- [self searchBar:searchBar activate:NO];
- }
- - (void)searchBar:(UISearchBar *)searchBar activate:(BOOL) active{
- if (!active) {
- [self.searchBar resignFirstResponder];
- }
- [self.searchBar setShowsCancelButton:active animated:YES];
- //修改UISearchBar取消按钮字体
- for (id aa in [searchBar subviews]) {
- if ([aa isKindOfClass:[UIButton class]]) {
- UIButton *btn = (UIButton *)aa;
- [btn setTitle:@"取消" forState:UIControlStateNormal];
- }
- }
- }
UISearchBar相关
时间: 2024-10-13 01:10:14