【问题标题】:How To Provide Search-As-You-Type Filtering With UICollectionView?如何使用 UICollectionView 提供 Search-As-You-Type 过滤?
【发布时间】:2013-01-15 21:54:48
【问题描述】:

我将 UICollectionView 添加到 ViewController。 UICollectionView 在每个单元格上显示带有人名的项目网格。 我想在您键入功能时添加搜索功能,当用户在 ViewController 上的搜索栏或 UITextField 中键入他们的名称时,该功能将过滤 UICollectionView,这样它就不会随着 UICollectionView 中的内容滚动。

尽管我在一些地方读到 UICollectionView 与 UITableView 相似,但我看不出在 UICollectionView 中实现此过滤器/搜索功能与在 UITableView 中的实现相同,并且需要一些帮助。

在您使用 UICollectionView 键入功能时,是否有人提供了执行此搜索/过滤的好示例?

【问题讨论】:

  • 尝试在 TableView 中研究搜索,了解 UISearchBar 并更改为 UICollectionView。如果遇到问题,请尝试提出另一个详细的问题。
  • 有人能解释一下怎么做吗?我还是不知道

标签: uitextfield uisearchbar uicollectionview


【解决方案1】:

我通过执行以下操作解决了它(希望对其他人有所帮助):

我将我的 UICollectionView 从 CoreData 填充到 NSArray:

self.allCVData = [context executeFetchRequest:fetchRequest error:&error];

然后将我的 NSArray 添加到 NSMutableArray 中,以便我可以使用它来过滤 UICollection:

self.filteredCVData =  [[NSMutableArray alloc] initWithArray:allCVData];

添加了一个 UITextField 并将其命名为 searchField。

在 viewDidLoad 中添加了一个选择器:

[mytextfield addTarget:self action:@selector(textDidChange:) forControlEvents:UIControlEventEditingChanged];

添加了接受 UITextField 更改的方法:

-(void) textDidChange:(id)sender
{

    UITextField* searchField = (UITextField *) sender;

    if(searchField.text.length == 0)
    {
        self.isFiltered = FALSE;
        [self.filteredCVData removeAllObjects];
        [self.filteredCVData addObjectsFromArray:self.allCVData];
    }
    else
    {
        self.isFiltered = true;
        [self.filteredCVData removeAllObjects];
        self.filteredCVData = [[NSMutableArray alloc] init];

        LogInfo(@"Before Looping in allCVData Array.");
        for (OLPerson* person in allCVData)
        {
            NSRange firstnameRange = [person.firstname rangeOfString:searchField.text options:NSCaseInsensitiveSearch];
            NSRange surnameRange = [person.surname rangeOfString:searchField.text options:NSCaseInsensitiveSearch];
            if(firstnameRange.location != NSNotFound || surnameRange.location != NSNotFound)
            {
                [self.filteredCVData addObject:person];
            }
        }
    }

    [self.collectionView reloadData];

}

【讨论】:

  • 是否需要手动移除一些UICollectionViewCell?在我的应用中,我只更改了数据源,它有时会崩溃。
  • @lenhhoxung 我确实在我的 UICollectionView 中使用了自定义 UICollectionViewCell。你说的“手动删除”是什么意思?
  • 是的,我使用了自定义 UICollectionViewCell。我的意思是我只需要更改数据源(数组)然后在 UICollectionView 上调用 reloadData 来更改单元格的数量。它可以工作,但有时会崩溃。
  • 类似:2014-01-08 01:38:47.004 Benbi[5441:907] *** 由于未捕获的异常“NSInternalInconsistencyException”而终止应用程序,原因:“无效更新:无效的项目数在第 0 节中。更新后现有节中包含的项目数 (26) 必须等于更新前该节中包含的项目数 (37) ...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-03-14
  • 1970-01-01
  • 1970-01-01
  • 2020-12-30
  • 1970-01-01
  • 2012-08-21
  • 2022-01-03
相关资源
最近更新 更多