设置UISearchBar的背景颜色

1、先进行图片的生成(代码生成),也可以通过UI设计师预先切好的图片。

/**
 *  生成图片
 *
 *  @param color  图片颜色
 *  @param height 图片高度
 *
 *  @return 生成的图片
 */
- (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;
}

2、然后就可以设置了

UIImage* searchBarBg = [self GetImageWithColor:[UIColor clearColor] andHeight:32.0f];
//设置背景图片
[_searchBar setBackgroundImage:searchBarBg];
//设置背景色
[_searchBar setBackgroundColor:[UIColor clearColor]];
//设置文本框背景
[_searchBar setSearchFieldBackgroundImage:searchBarBg forState:UIControlStateNormal];

OK,这样就大功告成了!

其他设置

1、设置字体颜色、默认字体颜色等

UITextField *searchField = [_searchBar valueForKey:@"_searchField"];
searchField.textColor = [UIColor whiteColor];
[searchField setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];

2、修改放大镜

UIImage *image = [UIImage imageNamed:@"cl_tab2_gray"];
UIImageView *iconView = [[UIImageView alloc] initWithImage:image];
iconView.frame = CGRectMake(0, 0, image.size.width , image.size.height);
searchField.leftView = iconView;

results matching ""

    No results matching ""