温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何在iOS中使用UITextField自定义搜索框

发布时间:2021-03-20 15:44:22 来源:亿速云 阅读:335 作者:Leah 栏目:移动开发

如何在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];

看完上述内容,你们掌握如何在iOS中使用UITextField自定义搜索框的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI