使用KVC自定义UISearchBar的UI

在日常工作中对于UISearchBar的操作主要集中在:

  • 设置UISearchBar中textfiled的边框及圆角
  • 设置占位文字的大小及颜色
  • 设置输入文字的大小及颜色
  • 修改搜索图标
  • 修改取消按钮的文本
  • ....

实现的方式有很多,就设置边框而言:可以设置背景图片实现效果;或者直接用UITextField来代替UISearchBar等等。但是以上的操作主要是集中在UISearchBar内部的UITextField上,因此获取到UISearchBar内部的UITextField便可以实现以上的效果:

  • 通过KVC获取子视图
UISearchBar *searchBar = [[UISearchBar alloc]init];
// 获取内部子视图
UITextField *searchField = [searchBar valueForKey:@"_searchField"]; 
UIView *backgroundView = [searchBar valueForKey:@"_background"];
UIButton *cancelButton = [searchBar valueForKey:@"_cancelButton"];
  • 改变输入框文本
UITextField *searchField = [searchBar valueForKey:@"_searchField"]; 

// 设置输入文字的大小及颜色
searchField.font = font(12);
searchField.textColor = UIColorRgb(32,32,32);

// 设置占位文字的大小及颜色
[searchField setValue:UIColorRgb(197,197,197) forKeyPath:@"_placeholderLabel.textColor"];
  • 设置输入框边框及圆角
UITextField *searchField = [searchBar valueForKey:@"_searchField"]; 

// 设置边框及圆角
searchField.layer.cornerRadius = 4.0f;
searchField.layer.masksToBounds = YES;
searchField.layer.borderWidth = 0.5f;
searchField.layer.borderColor = UIColorRgbAlpha(95,96,108,0.2).CGColor;
  • 设置输入框内搜索图标
UITextField *searchField = [searchBar valueForKey:@"_searchField"]; 

// 设置searchField上的搜索图标
UIImage *image = [UIImage imageNamed:@"search"];
UIImageView *iView = [[UIImageView alloc] initWithImage:image];
iView.frame = CGRectMake(0, 0, 15, 15);
searchField.leftView = iView;
  • 改变取消按钮的title
UIButton*cancelButton = [searchBar valueForKey:@"_cancelButton"];
[cancelButton setTitle:@"Close"forState:UIControlStateNormal];

你可能感兴趣的:(使用KVC自定义UISearchBar的UI)