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

来源:互联网 发布:互动百科排名优化 编辑:程序博客网 时间:2024/06/05 19:22

当我们需要搜索功能时,我们首先想到的肯定是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;    }];

这里写图片描述

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

1 0
原创粉丝点击