前言
公司决定对界面升级,统一UI,由于系统的UISearchBar太丑了,只能自定义了
实现DHSearchBarView
自定义DHSearchBarView,界面如下
image.png
显而易见 里面有searchBarView,searchImageView,searchTextField
这里说下DHSearchBarView的两个block回调,考虑到需求中会有时时搜索和点击reture键搜索,所以有两个回调代码如下
@property (nonatomic, strong) void (^textFieldDidChangeCallBack)(DHSearchBarView *searchBarView, NSString *content);
@property (nonatomic, strong) void (^textFieldReturnCallBack)(DHSearchBarView *searchBarView, NSString *content);
实现分类
直接用xib方式在controller中加载,这没问题
但考虑到我们项目中不少地方都会用到搜索框
所以可以使用分类的方法实现
给Controller添加分类 UIViewController+SearchBarView 代码如下
.h中的代码
@interface UIViewController (SearchBarView)
@property (nonatomic, strong, nullable) DHSearchBarView *dh_searchBarView;
- (DHSearchBarView *)addSearchBarViewWithPlaceHolder:(NSString * __nullable)placeHolder;
@end
.m中的代码
static NSString *searchBarViewKey = @"DHSearchBarView";
@implementation UIViewController (SearchBarView)
- (DHSearchBarView *)addSearchBarViewWithPlaceHolder:(NSString * __nullable)placeHolder
{
if (!self.dh_searchBarView) {
self.dh_searchBarView = [DHSearchBarView allocInitFormXib];
}
self.dh_searchBarView.searchTextField.placeholder = placeHolder;
[self.view addSubview:self.dh_searchBarView];
[self.dh_searchBarView mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.right.top.mas_equalTo(self.view);
make.height.mas_equalTo(@(40));
}];
return self.dh_searchBarView;
}
#pragma mark - getter && setter
- (DHSearchBarView *)dh_searchBarView
{
return objc_getAssociatedObject(self, &searchBarViewKey);
}
- (void)setDh_searchBarView:(DHSearchBarView *)dh_searchBarView
{
objc_setAssociatedObject(self, &searchBarViewKey, dh_searchBarView, OBJC_ASSOCIATION_RETAIN);
}
@end
解析
- .h中创建实体类 dh_searchBarView
名字加上了dh_ 为了防止和controller中的名字重名 - .m中实现set get方法
使用rumtime机制中的 objc_setAssociatedObject和objc_getAssociatedObject实现 - .m中添加方法addSearchBarViewWithPlaceHolder
使用时可以返回创建好的DHSearchBarView 方便在contorller中处理数据,或者修改控件的一些样式
使用
代码如下
kWeakself
DHSearchBarView *searchBarView = [self addSearchBarViewWithPlaceHolder:@"请输入关键词或编号进行搜索"];
searchBarView.textFieldDidChangeCallBack = ^(DHSearchBarView * _Nonnull searchBarView, NSString * _Nonnull content) {
weakself.contract_name = content;
weakself.pageIndex = 1;
[weakself loadDataWithAnimation:NO text:weakself.contract_name];
};
}
思考
1.使用分类更简单,只要项目引用分类,在添加一句代码 即可实现功能
2.分类能使代码更简单流畅
2021.7.7
完全可以将UIViewController+SearchBarView分类的代码,直接添加到DHSearchBarView中,更加简单便捷
网友评论