zoukankan      html  css  js  c++  java
  • 自定义UISearchBar

    事先声明一下,本篇的实现效果是在今年八月份未发布iOS8.0之前,自己根据项目需求修改的。而后在十月份发布的iOS8之后并没有做相应修改仍然是适配的,所以大致修改是类似的。

    通常在使用UISearchBar的时候大多都需要修改系统默认的背景色和自定义风格来与自己的app相适配。由于系统风格实在太丑了,但是UISearchBar的构造随着iOS版本的升级也在不断地改变。所以需要对不用版本的iOS做适配,这里来记录一下相关要点。

    首先来看一下效果图:上边为未修改系统默认的,下边则是自定义修改之后的样式效果。当然我们还可以根据自己自定义出更美观的界面出来。

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

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

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

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

    for (UIView *view in self.searchBar.subviews) {
      // for before iOS7.0
      if ([view isKindOfClass:NSClassFromString(@"UISearchBarBackground")]) {
        [view removeFromSuperview];
        break;
      }
      // for later iOS7.0(include)
      if ([view isKindOfClass:NSClassFromString(@"UIView")] && view.subviews.count > 0) {
        [[view.subviews objectAtIndex:0] removeFromSuperview];
        break;
      }
    }
    

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

    if ([self.searchBar respondsToSelector:@selector(barTintColor)]) {
      if ([[[UIDevice currentDevice] systemVersion] doubleValue] >= 7.1) {
        //ios7.1
        [[[[self.searchBar.subviews objectAtIndex:0] subviews] objectAtIndex:0] removeFromSuperview];
        [self.searchBar setBackgroundColor:[UIColor clearColor]];
      }else{
        //ios7.0
        [self.searchBar setBarTintColor:[UIColor clearColor]];
        [self.searchBar setBackgroundColor:[UIColor clearColor]];
      }
    }else{
      //iOS7.0 以下
      [[self.searchBar.subviews objectAtIndex:0] removeFromSuperview];
      [self.searchBar setBackgroundColor:[UIColor clearColor]];
    }
    

    而更多关于自定义取消按钮的实现部分如下:

    iOS 7

    iOS 5/6  

    以下是本项目中修改的实现代码:

    - (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
    {
      searchBar.showsCancelButton = YES;
      UIButton *cancelButton;
      UIView *topView = self.searchBar.subviews[0];
      for (UIView *subView in topView.subviews) {
        if ([subView isKindOfClass:NSClassFromString(@"UINavigationButton")]) {
          cancelButton = (UIButton*)subView;
        }
      }
      if (cancelButton) {
        //Set the new title of the cancel button
        [cancelButton setTitle:@"取消" forState:UIControlStateNormal];
        cancelButton.tintColor = [UIColor grayColor];
      }
    }
    
  • 相关阅读:
    字符编码笔记:ASCII,Unicode和UTF8(转)
    如何让vs2005的网站编译成一个DLL
    全力奔跑
    工作心得之再谈“表现”
    IT外企那点事[转载]
    直面奋斗
    C#图片水印代码整理
    常用js代码
    一个很有趣的程序员等级考试题求循环小数
    String.Format(字符串输出格式)
  • 原文地址:https://www.cnblogs.com/leiming1001/p/5345922.html
Copyright © 2011-2022 走看看