版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/shaohua_lv/article/details/71605251
在开发过程中,UISearchBar属不多见的控件,在我们一般使用的是系统原生样式:
但是UI设计师可能想要的是这种:
可能你觉得很简单:觉得设置背景颜色,边框图标什么的;
先看设置背景颜色:
我们直接设置backgroundcolor并不生效:因为这样直接设置的是最后面一层视图,前面有层灰色视图是UISearchBarBackground;
所以使用原生的backgroundColor并不生效,
你发现后可能觉得很简单:直接设置UISearchBarBackground的背景图,但是我们看控件
他是一个ImageView,而且直接去设置背景颜色也是不生效的,苹果只给这个UISearchBarBackground暴露一个setImage接口。所以可以用Image和Color的转化来设置。
- (void)setBackgroundColor:(UIColor *)backgroundColor
{
self.backgroundImage = [self createImageWithColor:backgroundColor];
}
- (void)setContentInset:(UIEdgeInsets)contentInset
{
_contentEdgeInsets = contentInset;
[self setNeedsDisplay];
}
- (UIImage *)createImageWithColor:(UIColor *)color
{
CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect);
UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return theImage;
}
怎样设置UITextfield属性:
对于这个TextField,UISearchBar并没有给外部使用,但是可以通过视图层级关系:
我们可以获取UITextField通过以下方式:这样我们才能设置输入字体样式,对齐方式,光标属性等。
(1). 通过KVC键值获取;
self.searchTextField = [self valueForKey:@"_searchField"];
(2). 通过视图获取该子视图;
if (_searchTextField == nil) {
for(UIView* view in self.subviews)
{
for(id subview in view.subviews) {
if([subview isKindOfClass:[UITextField class]])
{
_searchTextField = subview;
return subview;
}
}
}
}
对于左侧视图的图片我们可以设置,但是大小呢?假如想要这样一个呢?
这就需要我们重写这个控件,我重写的控件包括以下接口和属性:
@interface SHSearchBar : UISearchBar
// 搜索输入框,可进行UITextField操作
// 修改字体大小,编辑代理等;
@property (nonatomic, strong) UITextField *searchTextField;
// 设置搜索框背景颜色;
@property (nonatomic, strong) UIColor *backgroundColor;
/* 设置左侧搜索View;
* 自定义设置搜索图标视图。
* 可以是Button imageView等等。可以通过此View设置搜索图标frame,样式,背景等等
* 设置优先级高于leftSearchIcon;
*/
@property (nonatomic, strong) UIView *leftSearchView;
// 设置左侧搜索按钮的icon,仅修改图片,
@property (nonatomic, strong) UIImage *searchIcon;
// 设置右侧清除按钮的icon,仅修改图片,
@property (nonatomic, strong) UIImage *clearIcon;
/* 设置中间编辑区的EdgeInsets,
* 默认frame.origin == (8.0, 6.0);不等于searchBar的bounds
* 可通过设置Inset修改Textfild的边距
*/
@property (nonatomic, assign) UIEdgeInsets contentEdgeInsets;
// 初始化控件
- (instancetype)initWithFrame:(CGRect)frame;
// 设置左侧搜索按钮的偏移量
- (void)setLeftSearchIconOffset:(UIOffset)offset;
// 设置左侧搜索按钮的Rect,自定义布局
- (void)setLeftSearchIconRect:(CGRect)rect;
// 设置右侧清除按钮的偏移量
- (void)setrithClearIconOffset:(UIOffset)offset;
- (void)setTintColor:(UIColor *)tintColor;
@end
如喜欢,欢迎下载。
我的GitHub代码地址: https://github.com/lvshaohua/SHSearchBar.git