iOS定制UISearchBar导航栏同步iOS11的方法

2020-01-21 03:19:09刘景俊

图中可以清楚看到知乎首页导航栏由2个button组成,搜索页面使用了textField,这类似上文提到的第三种思路。

实战

通过自定义SearchBar实现一个如下样式的导航栏

 

 

ios,UISearchBar,iOS11,定制导航栏,导航栏

先自定义一个UISearchBar的初始化方法,观察一下首页和搜索页的异同,像searchField的大小背景色是一致的,可以这部分可以直接给定,而placeholder是不一样的,所以应该在调用的时候提供。以此类推,新建一个OHSearchBar类,一个初始化方法


- (instancetype)initWithFrame:(CGRect)frame placeholder:(NSString *)placeholder textFieldLeftView:(UIImageView *)leftView showCancelButton:(BOOL)showCancelButton tintColor:(UIColor *)tintColor { 
 if (self = [super initWithFrame:frame]) {
  self.frame = frame;
  self.tintColor = tintColor; //光标颜色
  self.barTintColor = [UIColor whiteColor];
  self.placeholder = placeholder;
  self.showsCancelButton = showCancelButton;
  self.leftView = leftView; // 用来代替左边的放大镜
  [self setImage:[UIImage imageNamed:@"clear"] forSearchBarIcon:UISearchBarIconClear state:UIControlStateNormal]; // 替换输入过程中右侧的clearIcon
 }
 return self;
}

新建一个首页OHHomeViewController,设置导航栏的titleView和rightBarButton


// navigation buttom
 UIButton *messageButton = [UIButton buttonWithType:UIButtonTypeSystem];
 [messageButton setImage:[UIImage imageNamed:@"msg"] forState:UIControlStateNormal];
 messageButton.bounds = CGRectMake(0, 0, 30, 30);
 UIBarButtonItem *messageBarButton = [[UIBarButtonItem alloc] initWithCustomView:messageButton];
 self.navigationItem.rightBarButtonItem = messageBarButton;
 
 // search bar
 UIImageView *leftView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"scan"]];
 leftView.bounds = CGRectMake(0, 0, 24, 24);
 self.ohSearchBar = [[OHSearchBar alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 44)
            placeholder:@"点击我跳转"
          textFieldLeftView:leftView
           showCancelButton:NO
            tintColor:[UIColor clearColor]];
 self.navigationItem.titleView = self.ohSearchBar;

让我们来看下效果,左边为iOS 9,右边iOS 11

 

 
ios,UISearchBar,iOS11,定制导航栏,导航栏

 

这时候可以看到几处差异

    searchBar的高度 searchBar的textField的放大镜和文字位置 textField的圆角不一致 更细心的还会发现,textField的位置不一致

解决方法: 第一和第二个问题,判断设备是否是iOS 11,若是则设置其高度,不是则让其placeholder居左。关键代码如下