记录一篇曾经对开发帮助的文章,UISearchBar定制。

转自:http://blog.csdn.net/djl461260911/article/details/41855905?utm_source=tuicool

谢谢大神分享。

因为需求是定制如图所示的searchBar

我的实现方式如下:

    for (UIView *view in self.searchBar.subviews) {

        if ([view isKindOfClass:NSClassFromString(@"UIView")] && view.subviews.count > 0) {

            [[view.subviews objectAtIndex:0] removeFromSuperview];

            [[view.subviews objectAtIndex:0] setBackgroundColor:[UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:0.3]];

            [[view.subviews objectAtIndex:0] setFrame:CGRectMake(8, 8, 312, 27.5)];

 

            break;

        }

    }

 

主要受教育的文段摘录:

这里,介绍一个刚刚学到的技巧:我们可以使用UIView的私有方法recursiveDescription来看一下UI控件的视图层次结构,在控制台打印出它的继承关系。

如:po [self.searchBar recursiveDescription] 
打印结果如下:

从以上可以看出,在iOS7.0之前,UISearchbar视图里直接包含UISearchBarBackground和UISearchBarTextField两个视图,而在iOS7.0及之后,UISearchbar视图里包含的是一个UIView视图,然后UIView视图里面才是UISearchBarBackground和UISearchBarTextField两个视图。相当于做了一次View的封装。

所以去除UISearchbar视图里的UISearchBarBackground之后,UISearchbar的背景也就透明了,同时也可以自定义颜色等。
使用如下代码即实现目的:

 

  1. for (UIView *view in self.searchBar.subviews) {  
  2.     // for before iOS7.0  
  3.     if ([view isKindOfClass:NSClassFromString(@"UISearchBarBackground")]) {  
  4.         [view removeFromSuperview];  
  5.         break;  
  6.     }  
  7.     // for later iOS7.0(include)  
  8.     if ([view isKindOfClass:NSClassFromString(@"UIView")] && view.subviews.count > 0) {  
  9.         [[view.subviews objectAtIndex:0] removeFromSuperview];  
  10.         break;  
  11.     }  
  12. }  

而对于以上项目截图的实现效果,并没有使用以上这段实现。而是判断系统版本使用如下部分代码:

 

 

    1. if ([self.searchBar respondsToSelector:@selector(barTintColor)]) {  
    2.     if ([[[UIDevice currentDevice] systemVersion] doubleValue] >= 7.1) {  
    3.         //ios7.1  
    4.         [[[[self.searchBar.subviews objectAtIndex:0] subviews] objectAtIndex:0] removeFromSuperview];  
    5.         [self.searchBar setBackgroundColor:[UIColor clearColor]];  
    6.     }else{  
    7.         //ios7.0  
    8.         [self.searchBar setBarTintColor:[UIColor clearColor]];  
    9.         [self.searchBar setBackgroundColor:[UIColor clearColor]];  
    10.     }  
    11. }else{  
    12.     //iOS7.0 以下  
    13.     [[self.searchBar.subviews objectAtIndex:0] removeFromSuperview];  
    14.     [self.searchBar setBackgroundColor:[UIColor clearColor]];  
    15. }  
posted @ 2015-08-26 15:53  Vick-Jo  阅读(118)  评论(0编辑  收藏  举报