最近在项目中遇到需要自定义搜索框的问题,试了很多方法,今天才总算解决了,积累经验,总结一番。
比如这种样式
代码如下
- (void)createSearchBar{
searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake((self.view.frame.size.width-300)/2, 100, 300, 40)];
searchBar.delegate = self;
searchBar.placeholder = [NSString stringWithCString:"搜索" encoding:NSUTF8StringEncoding];
//设置searchBar的背景色
UIImage * searchBarBg1 = [self GetImageWithColor:[UIColor whiteColor] andHeight:40];
[searchBar setBackgroundImage:searchBarBg1];
[searchBar setBackgroundColor:[UIColor clearColor]];
//设置输入框的背景色
UIImage * searchBarBg2 = [self GetImageWithColor:[UIColor greenColor] andHeight:40];
[searchBar setSearchFieldBackgroundImage:searchBarBg2 forState:UIControlStateNormal];
//设置字体颜色/大小,和圆角边框
UITextField *searchField = [searchBar valueForKey:@"_searchField"];
searchField.textColor = [UIColor grayColor];
[searchField setValue:[UIColor grayColor] forKeyPath:@"_placeholderLabel.textColor"];
searchField.font = [UIFont systemFontOfSize:17];
searchField.layer.cornerRadius = searchBar.frame.size.height/2;
searchField.layer.masksToBounds = YES;
[searchBar setContentMode:UIViewContentModeLeft];
[self.view addSubview:searchBar];
}
//生成图片
- (UIImage*) GetImageWithColor:(UIColor*)color andHeight:(CGFloat)height
{
CGRect r= CGRectMake(0.0f, 0.0f, 1.0f, height);
UIGraphicsBeginImageContext(r.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, r);
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return img;
}