UISearchBar去除背景
我们使用系统提供的UISearchBar时候创建出来的搜索框是这样的。
Snip20160728_16.png
这里我把它设置成了红色的边框。默认是灰色的那种
我们觉得灰色那一坨真挫。于是想办法去除那个边框
Snip20160728_17.png
这里不需要自定义。不过这里有点特殊。特殊在iOS版本不同的话UISearchBar的子控件是不同的
iOS 7.0以上有两层subviews iOS 7.0以下只有一层 而iOS7.0刚好没有
直接上代码
Snip20160728_18.png
Snip20160728_19.png
self.view.backgroundColor = [UIColor greenColor]; UISearchBar *search = [[UISearchBar alloc] initWithFrame:CGRectMake(100, 200, 200, 40)]; search.placeholder = @"请输入搜索条件"; [self.view addSubview:search]; //找出文本框 并且设置背景为orangeColor for (UIView *obj in [search subviews]) { for (UIView *objs in [obj subviews]) { if ([objs isKindOfClass:NSClassFromString(@"UITextField")]) { [objs setBackgroundColor:[UIColor orangeColor]]; } } if ([obj isKindOfClass:NSClassFromString(@"UITextField")]) { [obj setBackgroundColor:[UIColor orangeColor]]; } } //判断是哪个版本 7.0以上有两层subviews 7.0以下只有一层 而7.0刚好没有 float version = [[[UIDevice currentDevice] systemVersion] floatValue]; if (version == 7.0) { search.backgroundColor = [UIColor clearColor]; search.barTintColor = [UIColor clearColor]; } else { for (int i = 0; i < search.subviews.count; i++) { UIView *backView = search.subviews[i]; //7.0以下只有一层 if ([backView isKindOfClass:NSClassFromString(@"UISearchBarBackground")] == YES) { [backView removeFromSuperview]; [search setBackgroundColor:[UIColor clearColor]]; break; } //7.0以上有两层 else { NSArray *arr = search.subviews[i].subviews; for (int j = 0; j < arr.count; j++) { UIView *barView = arr[i]; if ([barView isKindOfClass:NSClassFromString(@"UISearchBarBackground")]) { [barView removeFromSuperview]; [search setBackgroundColor:[UIColor clearColor]]; break; } } } } }
还有另外种写法 我这里就写出下面 和上面效果一样,只不过写法上看起来不是没上面这种容易懂而已
Snip20160728_20.png
顺便附上代码:
UISearchBar *_searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(100, 300, 200, 40)]; _searchBar.placeholder = @"哈哈"; [self.view addSubview:_searchBar]; //当前版本号 float version = [[[UIDevice currentDevice]systemVersion]floatValue]; if([_searchBar respondsToSelector:@selector(barTintColor)]) { float iosversion7_1 = 7.1; if(version >= iosversion7_1) { [[[[_searchBar.subviews objectAtIndex:0]subviews]objectAtIndex:0]removeFromSuperview]; [_searchBar setBackgroundColor:[UIColor clearColor]]; } else{//iOS7.0 [_searchBar setBarTintColor:[UIColor clearColor]]; [_searchBar setBackgroundColor:[UIColor clearColor]]; } } else{ //iOS7.0以下 [[_searchBar.subviews objectAtIndex:0]removeFromSuperview]; [_searchBar setBackgroundColor:[UIColor clearColor]]; }