利用UITextField自定义搜索栏,实现中文输入过程中字母的搜索功能

当我们需要搜索功能时,我们首先想到的肯定是searchBar(当然我还只是个新手),但当我们需要在中文输入过程中搜索字母的时候时,searchBar就不好用了,只有当文字展示在searchBar上时,才会触发textDidChange的代理方法。
这时可以用UITextField自定义搜索栏,来实现我们的需求。
首先,先来实现searchBar成为第一响应者时搜索图标从中心移动到头部的动画:

self.searchBar.delegate = self;
    self.textField.delegate = self;
    self.textField.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
    self.textField.leftViewMode = UITextFieldViewModeAlways;
    [self.textField addSubview:self.imageView];

然后再重写imageView的get方法:

- (UIImageView *)imageView
{
    if (!_imageView) {
        _imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"search"]];
        _imageView.bounds = CGRectMake(0, 0, 20, 20);
        _imageView.center = CGPointMake([[UIScreen mainScreen] bounds].size.width/2, 15);
    }
    return _imageView;
}

这样我们textField的中心就会出现一个搜索图标了。
再在textField的代理方法中实现动画:

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [UIView animateWithDuration:0.2 animations:^{
        self.imageView.center = CGPointMake(15, 15);
    } completion:^(BOOL finished) {

    }];
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    if (textField.text.length == 0) {
        [UIView animateWithDuration:0.2 animations:^{
            self.imageView.center = CGPointMake([[UIScreen mainScreen] bounds].size.width/2, 15);
        } completion:^(BOOL finished) {

        }];
    }
}

至此我们就完成了textField的动画,然后我们只需要再获取textField上的文字,再根据自己的需求实现就OK了。
我这里用的RAC实现的文字变化时的响应:

[self.textField.rac_textSignal subscribeNext:^(NSString *text) {
        //这里实现一些功能就OK了,比如我是改变label的text
        self.label.text = text;
    }];

这里写图片描述

本博客原创并仅作笔记,转载请注明出处。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值