前段时间尝试了UISearchController,自带的动画效果非常好。微信的搜索目前就是用这个。
但是项目的SearchBar用在导航栏,UISearchController不太适用了。
UISearchBar *searchBar = [[UISearchBar alloc]init];
_searchBar = searchBar;
[searchBar setPlaceholder:@" 搜索医院名称"];
_searchBar.delegate = self;
[_searchBar setBackgroundColor:[UIColor whiteColor]];
[searchBar setBackgroundImage:[UIImage imageWithColor:[UIColor whiteColor]]];
//调整搜索图片向右偏移8
[searchBar setPositionAdjustment:UIOffsetMake(8, 0) forSearchBarIcon:UISearchBarIconSearch];
//获取textField(也可以通过KVC获取)
UITextField *searchField=[((UIView *)[searchBar.subviews objectAtIndex:0]).subviews lastObject];
//设置placeHolder字体的颜色
[searchField setValue:[UIColor colorWithString:@"#CCCCCC"]forKeyPath:@"_placeholderLabel.textColor"];
searchField.layer.cornerRadius = 14;
searchField.layer.masksToBounds = YES;
searchField.layer.borderWidth = 0.8;
searchField.layer.borderColor = [[UIColor colorWithString:@"#D7D7D7"] CGColor];
searchField.backgroundColor = [UIColor whiteColor];
searchBar.frame = CGRectMake(0, 0, SCREENW, 44);