UISearchController - 如何从筛选表中选择结果

问题描述 投票:1回答:4

我正在努力将搜索栏添加到现有应用中。

我有一个表填充了从服务器下载的数据,我正在使用新的UISearchController。

我现在所有搜索栏都完全正常工作,并在用户键入搜索栏时显示新的结果过滤表。

我的问题是如何处理用户从这个新的过滤搜索结果表中选择一个项目?

我从我的过滤表中添加了一个新的segue,并添加了一个didSelectRowAtIndexPath,它确实可以正常工作 - 但是当用户从过滤后的表中选择一个项目时,搜索栏仍然存在,并在该点之后单击“取消”会导致应用程序崩溃。

所以我不确定我应该做什么以及我应该如何处理用户从过滤表中选择项目?

我是否按照我的方式保存,但在用户选择项目时添加一些代码来取消搜索栏?

或者我这样做是错误的,有一种方法可以将选择从过滤后的表格返回到用户选择过滤项目的主视图控制器表格?

一如既往的任何帮助,非常感谢!

ios uisearchcontroller
4个回答
2
投票

在初始化searchController之后,尝试设置searchController的以下属性,这将启用didSelectRowAtIndexPathUITableViewDelegate方法

searchController.dimsBackgroundDuringPresentation = false

1
投票

如您所知,任何表的选择都是在该方法下执行的

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

您需要做的就是在方法didSelectRowAtIndexPath:中添加一个条件,以区分“完整”数据表与“已过滤”数据表。

在下面的示例代码中,我使用名为UserData的Singleton来存储我的选择,但是有许多不同的实现,欢迎提出建议。 (我不会介绍单身人士,但如果你有兴趣,请查看马特加洛威的this blog)。

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (mySearchController.active) {
        // if the search bar is active use filteredData array
        [[UserData sharedUserData] setSelection:filteredData[indexPath.row]];
        // here you can add your segue code
    } else {
        // if search bar is not active then use the full data set
        [[UserData sharedUserData] setSelection:unfilteredData[indexPath.row]];
        // here you can add your segue code
    }

    // Optional:
    //  if you would like to add a checkmark for selection
    // first remove any existing checkmarks
    for (UITableViewCell *cell in [tableView visibleCells]) {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }

    // then add new check mark
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.accessoryType = UITableViewCellAccessoryCheckmark;

    // and lastly tell the selected cell to deselect
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

我希望这有帮助。如果您对此有任何疑问或建议,请与我们联系。 :)


0
投票

您可能正在尝试从表控制器中呈现新控制器。不要这样做,你应该从搜索栏控制器中呈现它。


0
投票

当用户选择过滤的表行时,尝试关闭搜索栏:

[yourSearchController.searchBar resignFirstResponder];
© www.soinside.com 2019 - 2024. All rights reserved.