我們使用系統提供的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]];
}
備注:
如果有不足或者錯誤的地方還望各位讀者批評指正,可以評論留言,筆者收到后第一時間回復。
QQ/微信:2366889552 /lan2018yingwei。
簡書號:凡塵一笑:[簡書]
http://www.lxweimin.com/users/0158007b8d17/latest_articles
感謝各位觀眾老爺的閱讀,如果覺得筆者寫的還湊合,可以關注或收藏一下,不定期分享一些好玩的實用的demo給大家。
文/凡塵一笑(簡書作者)
著作權歸作者所有,轉載請聯系作者獲得授權,并標注“簡書作者”。