把背景的灰色改成透明色
[[[[self.searchBar.subviews objectAtIndex:0]subviews]objectAtIndex:0]removeFromSuperview];
[self.searchBar setBackgroundColor:[UIColor clearColor]];
// 方法二
[searchBar setBackgroundImage:[[UIImage alloc]init]];
当searchBar进入编辑状态时显示取消的按钮,当非编辑状态时不显示取消按钮
-(void)SearchBarBase
{
self.searchBar=[[UISearchBar alloc]init];
self.searchBar.delegate=self;
self.searchBar.placeholder=@"搜素你的小区或大厦、街道名称";
[self.view addSubview:self.searchBar];
__weak typeof(self)weakself=self;
[self.searchBar mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(weakself.view.mas_top).with.mas_offset(64);
make.left.equalTo(weakself.view.mas_left);
make.right.equalTo(weakself.view.mas_right);
make.height.equalTo(@(44*HeigheScale));
}];
UIView *searchBarBackView =[[UIView alloc]init];
searchBarBackView.backgroundColor =[UIColor colorWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1];
[self.searchBar insertSubview:searchBarBackView atIndex:1];
[searchBarBackView mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(weakself.searchBar.mas_top);
make.left.equalTo(weakself.searchBar.mas_left);
make.right.equalTo(weakself.searchBar.mas_right);
make.bottom.equalTo(weakself.searchBar.mas_bottom);
}];
}
-(BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
[searchBar setShowsCancelButton:YES animated:YES];
for (UIView *v in searchBar.subviews)
{
if ([v isKindOfClass:[UIButton class]])
{
UIButton *btn = (UIButton *)v;
[btn setTitle:@"取消" forState:UIControlStateNormal];
[btn setTitleColor:[UIColor darkGrayColor] forState:0];
}
}
return YES;
}
-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
[searchBar setShowsCancelButton:NO animated:YES];
//取消成为第一响应者
[self.searchBar resignFirstResponder];
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
[searchBar setShowsCancelButton:NO animated:YES];
}
遍历searchBar的子控件,这样就可以操作你想要的自视图了
for(id subView in [self.searchBar subviews]){
if([subView isKindOfClass:[UIButton class]]){
UIButton btn = (UIButton )subView;
[btn setTitle:@"取消" forState:UIControlStateNormal];
}
}
网友评论