设置自带UISearchBar的背景颜色

UISearchBar的默认背景色是灰色的,配合一些界面UI时效果不太好,但是没有直接修改背景色的API调用.
网上搜索的方法多为iOS8前的修改方法.
例如:

[[searchBar.subviews objectAtIndex:0]removeFromSuperview];

或是

for (UIView *subview in searchBar.subviews)
{
    if([subview isKindOfClass:NSClassFromString(@"UISearchBarBackground")])
    {
        [subview rmoveFromSuperview];
    }

}

第一种方法我在iOS8下试过后,直接整个搜索框没了-_-|||
后来在网上看到一种比较靠谱的方法,直接设置搜索栏的背景图片.
下面先进行图片的生成,当然也可以通过用美工预先切好的图片.

/**
 *  生成图片
 *
 *  @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;
}

接下来进行设置

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

这样就可以成功了.

你可能感兴趣的:(设置自带UISearchBar的背景颜色)