iOSiOS那些事

使用KVC自定义UISearchBar的UI

2016-08-04  本文已影响499人  whbsspu

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

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

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;
UIButton*cancelButton = [searchBar valueForKey:@"_cancelButton"];
[cancelButton setTitle:@"Close"forState:UIControlStateNormal];
上一篇下一篇

猜你喜欢

热点阅读