有时我们可能会遇到这样的需求:如图
搜索框两边是圆形的,当然这样的效果有很多方法来实现,但是个人感觉有点麻烦,今天我们用UISearchBar来实现上面的效果;具体实现思路是我们得到UISearchBar的子视图UITextField来设置其圆角,在系统的UISearchBar中UITextfield是这样的命名的searchField所以我们只要利用KVC得到就可以,具体实现代码如下:
[objc]view plaincopy
UITextField*searchField = [selfvalueForKey:@"searchField"];
if(searchField) {
[searchFieldsetBackgroundColor:[UIColorwhiteColor]];
searchField.layer.cornerRadius=14.0f;//设置圆角具体根据实际情况来设置
searchField.layer.borderColor= [UIColorlightGrayColor].CGColor;//边框的颜色
searchField.layer.borderWidth=1;//边框的宽
searchField.layer.masksToBounds=YES;
}
这样我们就可以给UISearchBar设置成圆角了,很简单吧 !
我们还可以给它加个背景图片来去掉系统的使看起开更美观,代码如下:
[objc]view plaincopy
UIImage* searchBarBg = [ToolsGetImageWithColor:[UtilsgetColor:@BACKGROUND]andHeight:40.0f];
UITextField*searchField = [selfvalueForKey:@"searchField"];
if(searchField) {
[searchFieldsetBackgroundColor:[UIColorwhiteColor]];
searchField.layer.cornerRadius=14.0f;
searchField.layer.borderColor= [UIColorlightGrayColor].CGColor;
searchField.layer.borderWidth=1;
searchField.layer.masksToBounds=YES;
}
[selfsetBackgroundImage:searchBarBg];
self.searchBarStyle= UISearchBarStyleProminent;
至于这个方法
[Tools GetImageWithColor:[Utils getColor:@BACKGROUND] andHeight:40.0f];是另外写出来的工具代码如下:
[objc]view plaincopy
+ (UIImage*)GetImageWithColor:(UIColor*)colorandHeight:(CGFloat)height
{
CGRect r= CGRectMake(0.0f,0.0f,1.0f, height);
UIGraphicsBeginImageContext(r.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [colorCGColor]);
CGContextFillRect(context, r);
UIImage*img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
returnimg;
}
只要传进需要的颜色和高度就可自动生成UIImage;至于
UITextField *searchField = [self valueForKey:@"searchField"];怎么知道是searchField 大家可根据runtime得到答案;技术有限就写到这吧,希望大家多多指教!也可关注iOS半桶水技术公众号;实时收到我这个菜鸟写的文章