iOS 设置自带UISearchBar的背景颜色

iOS 设置自带UISearchBar的背景颜色

 

前言

起因是首先今天开始了一个新的项目,然后首页有个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;

转载于:https://my.oschina.net/fadoudou/blog/718281

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值