iOS 设置自带UISearchBar的背景颜色

作者: 王隆帅 | 来源:发表于2016-03-09 16:54 被阅读16296次

前言

起因是首先今天开始了一个新的项目,然后首页有个UITabBar而且背景是透明的,本来心想这也没啥,之前也做过不少类似的,直接复制粘贴不就OK了嘛!,然后粘过来后才发现代码都失效了(均为iOS8之前的修改方法),然后又各种百度、各种谷歌试了半天也没啥卵用,最后在一个角落发现一个方法修改成功,遂记录下来。

方法说明

此方法与之前的方法不同,之前的都是通过遍历将子View remove掉或者通过KVO来修改,所以当iOS系统版本发生变化的时候,可能就会受到影响(好像现在就受到了影响/(ㄒoㄒ)/~~)。本方法是直接设置搜索栏的背景图片,使用的是系统的API,风险明显就降低了吧。

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;

我的公众号二维码

相关文章

网友评论

  • 卓敦:楼主,为啥我这样设置之后,运行报警告
    *** warning calling -[UISearchBarTextField _applyRoundedRectBackgroundCornerRadiusToBackgroundViewWithWarning:] with unsupported background
  • Fintecher:上Appstore会被拒吗?
    王隆帅:@favormm 不用担心,之前的项目早就上线了
    Fintecher:@王隆帅 _searchField应该是没有公开的属性,属于私有API吧
    王隆帅:@favormm 为啥会被拒
  • 温暖的男人:O(∩_∩)O谢谢分享!
  • 可别:66666
  • 师景福:谢谢
  • 俊月:好用
  • 冰三尺:1、设置字体颜色、默认字体颜色等
    2、修改放大镜
    这两个是设置UISearchBar的吗? 不应该是修改UITextField的吗?

本文标题:iOS 设置自带UISearchBar的背景颜色

本文链接:https://www.haomeiwen.com/subject/xvxtlttx.html