设置之前:
设置之后:
代码如下:
// // ViewController.m // UISearchBarDemo // // Created by 思 彭 on 17/3/24. // Copyright © 2017年 思 彭. All rights reserved. // #import "ViewController.h" @interface ViewController ()<UISearchBarDelegate> @property (nonatomic, strong) UISearchBar *searchBar;/**<搜索框 */ @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; self.title = @"UISearchBar"; [self setupSearchBar]; [self setSearchBar]; } //添加搜索框 - (void)setupSearchBar { self.searchBar = [[UISearchBar alloc]init]; self.searchBar.frame = CGRectMake(0, 64, self.view.frame.size.width, 44); self.searchBar.delegate = self; // self.searchBar.searchBarStyle =UISearchBarStyleMinimal; self.searchBar.barTintColor = [UIColor colorWithRed:238.0/255 green:238.0/255 blue:238.0/255 alpha:1.0]; // 去除了分割线,需要设置背景颜色 self.searchBar.backgroundColor = [UIColor colorWithRed:238.0/255 green:238.0/255 blue:238.0/255 alpha:1.0]; [self.searchBar setAutocapitalizationType:UITextAutocapitalizationTypeNone]; self.searchBar.placeholder = @"搜索"; [self.searchBar sizeToFit]; UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapClick:)]; [self.navigationController.navigationBar addGestureRecognizer:tap]; [self.view addSubview:self.searchBar]; } // 去掉SearchBar上面两条线 - (void)setSearchBar { for (UIView *obj in [self.searchBar subviews]) { for (UIView *objs in [obj subviews]) { if ([objs isKindOfClass:NSClassFromString(@"UISearchBarBackground")]){ [objs removeFromSuperview]; } } if ([obj isKindOfClass:NSClassFromString(@"UISearchBarBackground")]){ [obj removeFromSuperview]; } } } #pragma marl - UISearchBarDelegate - (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar { self.searchBar.showsCancelButton = YES; return YES; } - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar { self.searchBar.showsCancelButton = NO; searchBar.text = @""; [self.searchBar resignFirstResponder]; } - (void)tapClick:(UITapGestureRecognizer *)tap { self.searchBar.showsCancelButton = NO; [self.searchBar resignFirstResponder]; } //点击搜索按钮 - (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar { self.searchBar.showsCancelButton = NO; [searchBar resignFirstResponder]; } @end