UISearchBar 一步实现

简而言之,UISearchBar是一个搜索控件,样式随着需求变化而变化,最近用到这个控件,我们的需求是这样的,每输入都要请求网络进行搜索,所以在工程中不需要点击搜索按钮,我大概做了一个简化,去掉了网络请求部分,改为本地数据的搜索。我的思路是这样的:创建UI(UISearchBar、UITableView),通过UISearchBar的代理方法中进行监听是否输入字符,然后进行谓词筛选,放入数组中,接着就是刷新tableView,把数据展示上去,Over~接着就是上代码。

@interface ViewController ()<UITableViewDelegate, UITableViewDataSource,UISearchBarDelegate>
{
    UISearchBar         *searchBar;         //搜索框
    NSArray             *data;              //所有数据数组
    NSMutableArray      *filterData;        //存放筛选出来的数组
    
}
/**  表视图 */
@property(nonatomic, strong) UITableView            *tableView;
@end
/**  根据屏幕比例进行适配(6s) */
#define kAutoLayoutHeight   (KScreenHeight / 667)
#define kAutoLayoutWidth (KScreenWidth / 375)
/**  屏幕宽度、高度 */
#define KScreenWidth [UIScreen mainScreen].bounds.size.width
#define KScreenHeight [UIScreen mainScreen].bounds.size.height
//自定义颜色
//#define JC_ARCM_COLOR [UIColor colorWithRed:arc4random() % 10 * 0.1 green:arc4random() % 10 * 0.1 blue:arc4random() % 10 * 0.1 alpha:1.0]
#define JC_ARCM_COLOR [UIColor clearColor]
@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    data = @[@{@"imgUrl":@"default_icon", @"name":@"张三"},
             @{@"imgUrl":@"default_icon", @"name":@"王二"},
             @{@"imgUrl":@"default_icon", @"name":@"赵虎"},
             @{@"imgUrl":@"default_icon", @"name":@"梅艳芳"},
             @{@"imgUrl":@"default_icon", @"name":@"12345"},
             @{@"imgUrl":@"default_icon", @"name":@"abcd"},
             @{@"imgUrl":@"default_icon", @"name":@"3478"},
             @{@"imgUrl":@"default_icon", @"name":@"cdcc"}];
    filterData = [[NSMutableArray alloc]init];
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    self.navigationController.navigationBar.translucent = NO;
    [self initSreachView];
    [self initTableViews];
}
#pragma mark -
#pragma mark - Search View
- (void)initSreachView
{
    searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(40, 20, KScreenWidth - 80 * kAutoLayoutWidth, 40)];
    searchBar.delegate = self;
    searchBar.showsCancelButton = NO;
    searchBar.placeholder = @"搜索借款平台";
//    [searchBar setImage:[UIImage imageNamed:@"account_search_icon"]
//            forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];
    //去掉边框
    for (UIView *view in searchBar.subviews) {
        // for before iOS7.0
        if ([view isKindOfClass:NSClassFromString(@"UISearchBarBackground")]) {
            [view removeFromSuperview];
            break;
        }
        // for later iOS7.0(include)
        if ([view isKindOfClass:NSClassFromString(@"UIView")] && view.subviews.count > 0) {
            [[view.subviews objectAtIndex:0] removeFromSuperview];
            break;
        }
    }
    [self.navigationController.view addSubview:searchBar];
    UITextField *searchField = [searchBar valueForKey:@"_searchField"];
    [searchField setBackgroundColor:[UIColor colorWithRed:242/255.0 green:242/255.0 blue:242/255.0 alpha:1.0]];//VC_COLOR
    searchField.layer.cornerRadius = 14.0f;
    searchField.layer.masksToBounds = YES;
    [searchField setValue:[UIColor colorWithRed:169/255.0 green:176/255.0 blue:186/255.0 alpha:1.0] forKeyPath:@"_placeholderLabel.textColor"];//B3_COLOR
}

#pragma mark -
#pragma mark - 表视图
- (void)initTableViews
{
    [self.view addSubview:self.tableView];
    self.tableView.frame = CGRectMake(0, 0, KScreenWidth, KScreenHeight);
//    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.right.bottom.equalTo(self.tableView.superview);
//        make.top.equalTo(self.tableView.superview).with.offset(-20);
//    }];
}
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.tableFooterView = [[UIView alloc]init];
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.separatorColor = [UIColor colorWithRed:225/255.0 green:229/255.0 blue:235/255.0 alpha:1.0];
    }
    return _tableView;
}

#pragma mark -
#pragma mark - UISearchBardelegete
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    
    NSLog(@"任务编辑文本");
    return YES;
}
// return NO to not become first responder
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
    
    NSLog(@"开始");
}
// called when text starts editing
- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar{
    
    return YES;
}
// return NO to not resign first responder
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{
    
    NSLog(@"编辑完成");
    
}
// called when text ends editing
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    //清空数组
    [filterData removeAllObjects];
    // 谓词搜索
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self contains [cd] %@", searchText];
    NSMutableArray *names = [[NSMutableArray alloc]init];
    for (NSDictionary *dic in data)
    {
        [names addObject:[dic objectForKey:@"name"]];
    }
    //筛选出来的名称
    NSArray *filterNames =  [[NSArray alloc] initWithArray:[names filteredArrayUsingPredicate:predicate]];
    NSLog(@"%@", filterNames);
    for (NSDictionary *dic in data)
    {
        for (NSString *name in filterNames)
        {
            if ([name isEqualToString:[dic objectForKey:@"name"]])
            {
                [filterData addObject:dic];
            }
        }
    }
    [_tableView reloadData];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    //    [searchDisplayController setActive:NO animated:YES];
    NSLog(@"点击完成");
}
// called when keyboard search button pressed
- (BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    return YES;
}

#pragma mark -
#pragma mark - UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return filterData.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *idetifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:idetifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:idetifier];
    }
    cell.backgroundColor = [UIColor whiteColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.textLabel.font = [UIFont systemFontOfSize:16.0];
    cell.textLabel.textColor = [UIColor colorWithRed:98/255.0 green:105/255.0 blue:113/255.0 alpha:1.0];
    cell.detailTextLabel.font = [UIFont systemFontOfSize:12.0];
    cell.detailTextLabel.textColor = [UIColor lightGrayColor];
    cell.imageView.image = [UIImage imageNamed:filterData[indexPath.row][@"imgUrl"]];
    cell.textLabel.text = filterData[indexPath.row][@"name"];
    cell.detailTextLabel.text = @"手动记账";
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"点击了第%zi行", indexPath.row);
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return CGFLOAT_MIN;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return CGFLOAT_MIN;
}
//点击空白区域取消键盘响应
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    UITextField *searchField = [searchBar valueForKey:@"_searchField"];
    [searchField resignFirstResponder];
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值