iOS 使用UITextField自定义搜索框 实现用户输入完之后“实时搜索”

注:CSDN的代码块有点捞,如果浏览器窗口较窄,一行代码占了两行的位置,后面的代码就看不到了,大家可以把浏览器窗口拉大一点

UI小姐姐设计的搜索框经常是五花八门,系统的搜索框经常不能满足我们的需求,需要我们特别定制一个。但是UITextField的诸多回调里面,没有一个是适合触发搜索时间的。
UITextFieldTextDidChangeNotification调用过于频繁,每输入一个字符就调一次接口怕是不太合适。
UITextFieldTextDidEndEditingNotification只有在结束编辑的时候才会调一次,结束编辑就意味着键盘消失了,也不太合适。
这样就难倒我们了吗,当然不是,办法还是有滴。

解决方案
先自定义一个搜索框 改好样式,然后监听UITextFieldTextDidChangeNotification

- (void)textFieldDidChange{
    if (self.searchDelegate && [self.searchDelegate respondsToSelector:@selector(customSearchBar:textDidChange:)]) {
        [self.searchDelegate customSearchBar:self textDidChange:self.text];
    }
}


使用

@property (nonatomic, strong) LGCustomSearchBar *searchBar;
@property (nonatomic, assign) NSInteger inputCount; 记录输入次数
- (void)viewDidLoad {
    [super viewDidLoad];
    self.searchBar = [[LGCustomSearchBar alloc] initWithFrame:CGRectMake(20, 10, kScreenWidth-40, 36)];
    self.searchBar.searchDelegate = self;
    [self.view addSubview:self.searchBar];
}

- (void)customSearchBar:(LGCustomSearchBar *)searchBar textDidChange:(NSString *)searchText{
    if (searchText.length == 0) {
        [self searchKeyword:@(self.inputCount)];
    }
    else{
        self.inputCount++;
        [self performSelector:@selector(searchKeyword:) withObject:@(self.inputCount) afterDelay:1.5f];
    }
}

- (void)searchKeyword:(NSNumber *)inputCount{

	// 判断不等于0是为了防止用户输入完直接点击搜索,延时结束之后又搜索一次
    if (inputCount.integerValue == self.inputCount && self.inputCount != 0) {
        [self loadData];
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self loadData];
    return NO;
}

- (void)loadData{
    self.inputCount = 0;
	// 本地查询 或者 请求数据
	...
    [self.tableView reloadData];
}



核心代码
延迟1.5秒以后执行搜索,判读如果1.5秒之后传入的输入次数和现在的输入次数一致,说明用户1.5秒已经没有输入新内容了,加在新数据。这个时间可以自己调整

[self performSelector:@selector(searchKeyword:) withObject:@(self.inputCount) afterDelay:1.5f];

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值