UISearchbar 颜色的自定义和圆角样式的制作

-(UIView *)tableheaderview{
    if (!_tableheaderview) {
        _serarbar = [[UISearchBar alloc] initWithFrame:CGRectMake(15, 8, kScreenW - 30 , 32)];
        _serarbar.placeholder = @"搜索机构名称";
        _serarbar.delegate = self;
        kRViewBorderRadius(_serarbar, 16)
        _serarbar.searchBarStyle = UISearchBarStyleMinimal;
        
        UITextField *searchField = [_serarbar valueForKey:@"_searchField"];
        searchField.textColor = khometextcolor;
        searchField.font = [UIFont systemFontOfSize:14];
        [searchField setValue:kgraycolor forKeyPath:@"_placeholderLabel.textColor"];
    
        UIImage *searchBarBg = [UIImage imageWithColor:[UIColor colorWithRGBA:0xfafaffff] size:CGSizeMake(kScreenW - 30, 32)];
        UIImage *radiusBg = [searchBarBg imageByRoundCornerRadius:16];
        [_serarbar setSearchFieldBackgroundImage:radiusBg forState:UIControlStateNormal];
        _tableheaderview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, 49)];
        [_tableheaderview addSubview:_serarbar];
        _tableheaderview.backgroundColor = kwhite;
    }
    return _tableheaderview;
}

先上代码

这里主要是三步:

1.创建uisearchbar  【关键的一步是】 

 _serarbar.searchBarStyle = UISearchBarStyleMinimal;//作用是是让背景色失效,详情可以用comond按键点进去看一下头文件中的表述

2.通过kvc设置searchfield 字体 placehoder颜色,输入的颜色和子弟大小等关于tf的相关属性设置  注意着两部都不设置背景色

3.创建一个背景图片,然后设置这个背景图片到这个searchbar上面去

-------

这里还需要说下生成图片的方法的解释

摘自YY分类

+ (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size {
    if (!color || size.width <= 0 || size.height <= 0) return nil;
    CGRect rect = CGRectMake(0.0f, 0.0f, size.width, size.height);
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, color.CGColor);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

后面图像圆角也是用的yy分类

imageByRoundCornerRadius

此外还用了个宏把view进行圆角处理

 kRViewBorderRadius(_serarbar, 16)
 

#define kRViewBorderRadius(View, Radius)\
\
[View.layer setCornerRadius:(Radius)];\
[View.layer setMasksToBounds:YES];\

至此一般符合视觉效果的uisearbar就可以设置完成

猜你喜欢

转载自blog.csdn.net/hccgk/article/details/84644691