分享

iOS 设置自带UISearchBar的背景颜色

 dxw121 2017-03-13

前言

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


我的公众号二维码

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多