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

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

查看视图层级会发现,iOS 11以下,设置titleView,x的默认坐标居然是12,而iOS 11是0。所以设置textField的x坐标的话,在iOS 11下必须多出12才会是一致的位置。

 

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

 

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

修改代码上面的代码


- (void)layoutSubviews{
 [super layoutSubviews];
 // search field
 UITextField *searchField = [self valueForKey:@"searchField"];
 searchField.backgroundColor = DARK_BLUE_COLOR;
 searchField.textColor = [UIColor whiteColor];
 searchField.font = [UIFont systemFontOfSize:16];
 searchField.leftView = self.leftView;
 if (@available(iOS 11.0, *)) {
  // 查看视图层级,在iOS 11之前searchbar的x是12
  searchField.frame = CGRectMake(12, 8, SCREEN_WIDTH*0.8, 28);

 } else {
  searchField.frame = CGRectMake(0, 8, SCREEN_WIDTH*0.8, 28);
 }
 searchField.borderStyle = UITextBorderStyleNone;
 searchField.layer.cornerRadius = 5;
 searchField.layer.masksToBounds = YES;
 [searchField setValue:[UIColor whiteColor] forKeyPath:@"placeholderLabel.textColor"];
 [self setValue:searchField forKey:@"searchField"];
  self.searchTextPositionAdjustment = (UIOffset){10, 0}; // 光标偏移量
}

这时候就是我们想要的结果了。

首页暂时告一段落,接着开始我们的搜索页面。与首页不同的是需要searchBar与searchController配合使用。新建一个OHSearchController类 添加一个属性


@property (nonatomic, strong) OHSearchBar *ohSearchBar;

初始化代码


- (instancetype)initWithSearchResultsController:(UIViewController *)searchResultsController searchBarFrame:(CGRect)searchBarFrame placeholder:(NSString *)placeholder textFieldLeftView:(UIImageView *)leftView showCancelButton:(BOOL)showCancelButton barTintColor:(UIColor *)barTintColor{
 if (self = [super initWithSearchResultsController:searchResultsController]) {
  self.ohSearchBar = [[OHSearchBar alloc] initWithFrame:searchBarFrame
             placeholder:placeholder
           textFieldLeftView:leftView
            showCancelButton:YES
             tintColor:barTintColor];
  
  UIButton *button = [self.ohSearchBar valueForKey:@"cancelButton"];
  button.tintColor = [UIColor whiteColor];
  [button setTitle:@"取消" forState:UIControlStateNormal];
  [self.ohSearchBar setValue:button forKey:@"cancelButton"];
 }
 return self;
}

接着是我们的视图控制器OHSearchViewController


UIImageView *leftView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"search"]];
 leftView.bounds = CGRectMake(0, 0, 24, 24);
 self.ohSearchController = [[OHSearchController alloc] initWithSearchResultsController:self
                   searchBarFrame:CGRectMake(0, 0, SCREEN_WIDTH, 44)
                    placeholder:@"请输入搜索内容进行搜索"
                  textFieldLeftView:leftView
                   showCancelButton:YES
                    barTintColor:BASE_BLUE_COLOR];
 
 [self.ohSearchController.ohSearchBar becomeFirstResponder];
 self.ohSearchController.ohSearchBar.delegate = self;
 [self.ohSearchController.ohSearchBar setLeftPlaceholder];
 self.navigationItem.titleView = self.ohSearchController.ohSearchBar;
 self.navigationItem.hidesBackButton = YES;