简体   繁体   English

如何在保持UISearchBar活动的同时强制UITableView重新加载数据?

[英]How can I force a UITableView to reloadData while keeping a UISearchBar active?

I've got a UITableView that has 20 sections. 我有一个有20个部分的UITableView。 At the top I have a UISearchBar, and I want to filter the sections live as the user types. 在顶部我有一个UISearchBar,我想在用户输入时过滤部分。

Unfortunately, if the UISearchBar is active and if I return NO from searchBarShouldEndEditing: then my [tableView reloadData] call is ignored. 不幸的是,如果UISearchBar处于活动状态并且我从searchBarShouldEndEditing返回NO:则忽略我的[tableView reloadData]调用。 If I return YES from searchBarShouldEndEditing: then the reloadData call works fine but I lose firstResponder after each character typed. 如果我从searchBarShouldEndEditing返回YES:那么reloadData调用工作正常,但在每个字符输入后我丢失firstResponder。

How can I force the UITableView to do live updates and filtering without having to resignFirstResponder on the UISearchBar between each character typed? 如何强制UITableView进行实时更新和过滤,而不必在每个键入的字符之间在UISearchBar上使用resignFirstResponder?

I faced the same problem and ended up with a quite elegant solution : 我遇到了同样的问题,最终找到了一个非常优雅的解决方案:

You place your search bar in a specific section of your table (let's say index 0). 您将搜索栏放在表格的特定部分(比如索引0)。 You place your table data in another section (let's say index 1). 您将表数据放在另一个部分(比如索引1)。

When the text of your search bar changes, you can update your model and then simply call : 当搜索栏的文本发生变化时,您可以更新模型,然后只需调用:

NSIndexSet *indexSet = [NSIndexSet indexSetWithIndex:1];
[self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];

This way, your keyboard will still be active, your search bar will still be the first responder, and you will benefit from nice built-in table animations ! 这样,你的键盘仍然是活动的,你的搜索栏仍然是第一个响应者,你将受益于漂亮的内置表动画!

You could save yourself a lot of work by using the UISearchDisplayController and just feeding it the same datasource. 通过使用UISearchDisplayController并为其提供相同的数据源,您可以节省大量的工作。 It manages the search bar and its own table view for displaying filtered results. 它管理搜索栏及其自己的表视图,以显示筛选结果。

I had similar problem. 我有类似的问题。 It turned out that it had to do with animations I used when table was reloading data. 事实证明,这与我在表重新加载数据时使用的动画有关。 When I removed reloadSections:withRowAnimation , and simply called: 当我删除reloadSections:withRowAnimation ,并简单地调用:

[self.tableView reloadData];

instead of calling fancier methods with animations for refreshing the table data, the search bar did not resign first responder on any key entered anymore. 搜索栏不再使用动画调用用于刷新表数据的动画方法,而是不再对输入的任何键上的第一响应者进行重新签名。

Hope this helps... 希望这可以帮助...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM