草庐IT

ios - 在具有多个部分的 UITableView 中从 UISearchBar 按类型搜索?

coder 2024-01-16 原文

所以我目前正在收听来自 searchBar 的文本更改:

-(void)searchBar:(UISearchBar*)searchBar textDidChange:(NSString*)searchText
{    
      [self filterContentForSearchText:searchText]; 
}

我想设计一个方法 filterContentForsearchText 以便它在我键入时自动过滤我的 UITableView。

我遇到的问题是我的 UITableView 很复杂。它有多个部分和多个字段。它基本上是一个联系人/地址簿,是一个包含联系人对象的数组。

CustomContact *con = [contacts[section_of_contact] allValues][0][x] 其中 x 是该部分中的特定行返回具有 con 等属性的 CustomContact“con” .fullName.

UITableView 目前在单独的部分中显示联系人的全名。我如何在使用 UISearchBar 键入时过滤数组/UITableView 的这种结构?

表格的填充方式如下:

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    BrowseContactCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BROWSECELL"];

    CustomContact *thisContact = [self.contacts[indexPath.section] allValues][0][indexPath.row];

        cell.labelName.text = thisContact.fullName;

return cell;
}

最佳答案

我还创建了一个包含部分(数组的数组)的地址簿,所以我只发布我的解决方案,但这不是我自己的解决方案(我前段时间在 stackoverflow 的某个地方找到它):

在您的 UITableViewController 子类中,只需添加以下两个 UISearchDisplayDelegate 方法 ( link to the api reference ) 和“自定义”方法 filterContentForSearchText 进行过滤你的阵列。为了更好地理解,请阅读我在代码块中的评论。欢迎提出更多问题或提出改进意见。

#pragma mark - search Display Controller Delegate

- (BOOL) searchDisplayController : (UISearchDisplayController *) controller
shouldReloadTableForSearchString : (NSString *) searchString {

    [self filterContentForSearchText : searchString
                               scope : [[self.searchDisplayController.searchBar scopeButtonTitles]
                       objectAtIndex : [self.searchDisplayController.searchBar selectedScopeButtonIndex]]];
    return YES;
}

#pragma mark - Search Filter

- (void) filterContentForSearchText : (NSString*) searchText
                              scope : (NSString*) scope {
    // Here, instead of "lastName" or "firstName" just type your "fullName" a.s.o.
    // I have also a custom NSObject subclass like your CustomContact that holds 
    //these strings like con.firstName or con.lastName
    NSPredicate* resultPredicate = [NSPredicate predicateWithFormat : @" (lastName beginswith %@) OR (firstName beginsWith %@)", searchText, searchText];

    // For this method, you just don't need to take your partitioned and 
    // somehow complicated contacts array (the array of arrays). 
    // Instead, just take an array that holds all your CustomContacts (unsorted):
    NSArray* contactsArray = // here, get your unsorted contacts array from your data base or somewhere else you have stored your contacts;

    // _searchResults is a private NSArray property, declared in this .m-file 
    // you will need this later (see below) in two of your UITableViewDataSource-methods:
    _searchResults = [contactsArray filteredArrayUsingPredicate : resultPredicate];

    // this is just for testing, if your search-Filter is working properly.
    // Just remove it if you don't need it anymore
    if (_searchResults.count == 0) {
        NSLog(@" -> No Results (If that is wrong: try using simulator keyboard for testing!)");
    } else {
        NSLog(@" -> Number of search Results: %d", searchResults.count);
    }
}

现在,您需要对以下三个 UITableViewDataSource 方法进行一些更改:

注意:searchResultsTableView也加载了普通的公共(public)数据源 通常调用的方法来填充您的(分段地址簿)tableView:

1.

- (NSInteger) numberOfSectionsInTableView : (UITableView *) tableView
{
    if (tableView == self.searchDisplayController.searchResultsTableView) {
         // in our searchTableView we don't need to show the sections with headers
        return 1;
    }
    else {
        return [[[UILocalizedIndexedCollation currentCollation] sectionTitles] count];
    }
}

2.

- (NSInteger) tableView : (UITableView *) tableView
  numberOfRowsInSection : (NSInteger) section {

    if (tableView == self.searchDisplayController.searchResultsTableView) {
        // return number of search results
        return [_searchResults count];
    } else {
        // return count of the array that belongs to that section
        // here, put (or just let it there like before) your 
        // [contacts[section] allValues][count]
       return [[currentMNFaces objectAtIndex : section] count];
    }    
}

3.

- (UITableViewCell*) tableView : (UITableView *) tableView
          cellForRowAtIndexPath : (NSIndexPath *) indexPath {

    BrowseContactCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BROWSECELL"];
CustomContact *thisContact = nil;

    // after loading your (custom) UITableViewCell
    // you probably might load your object that will be put into the 
    // labels of that tableCell.
    // This is the point, where you need to take care if this is your
    // address-book tableView that is loaded, or your searchTable:

    // load object...    
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        // from search list
        faceAtIndex = [self->searchResults objectAtIndex: indexPath.row];
    } else {
        // from your contacts list
        contactAtIndex = [self.contacts[indexPath.section] allValues][0][indexPath.row];
    }

    }

希望对你有用。

关于ios - 在具有多个部分的 UITableView 中从 UISearchBar 按类型搜索?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17032263/

有关ios - 在具有多个部分的 UITableView 中从 UISearchBar 按类型搜索?的更多相关文章

  1. ruby-on-rails - Rails 3 中的多个路由文件 - 2

    Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题

  2. ruby - 具有身份验证的私有(private) Ruby Gem 服务器 - 2

    我想安装一个带有一些身份验证的私有(private)Rubygem服务器。我希望能够使用公共(public)Ubuntu服务器托管内部gem。我读到了http://docs.rubygems.org/read/chapter/18.但是那个没有身份验证-如我所见。然后我读到了https://github.com/cwninja/geminabox.但是当我使用基本身份验证(他们在他们的Wiki中有)时,它会提示从我的服务器获取源。所以。如何制作带有身份验证的私有(private)Rubygem服务器?这是不可能的吗?谢谢。编辑:Geminabox问题。我尝试“捆绑”以安装新的gem..

  3. ruby-on-rails - 在 Ruby 中循环遍历多个数组 - 2

    我有多个ActiveRecord子类Item的实例数组,我需要根据最早的事件循环打印。在这种情况下,我需要打印付款和维护日期,如下所示:ItemAmaintenancerequiredin5daysItemBpaymentrequiredin6daysItemApaymentrequiredin7daysItemBmaintenancerequiredin8days我目前有两个查询,用于查找maintenance和payment项目(非排他性查询),并输出如下内容:paymentrequiredin...maintenancerequiredin...有什么方法可以改善上述(丑陋的)代

  4. ruby-on-rails - Rails - 一个 View 中的多个模型 - 2

    我需要从一个View访问多个模型。以前,我的links_controller仅用于提供以不同方式排序的链接资源。现在我想包括一个部分(我假设)显示按分数排序的顶级用户(@users=User.all.sort_by(&:score))我知道我可以将此代码插入每个链接操作并从View访问它,但这似乎不是“ruby方式”,我将需要在不久的将来访问更多模型。这可能会变得很脏,是否有针对这种情况的任何技术?注意事项:我认为我的应用程序正朝着单一格式和动态页面内容的方向发展,本质上是一个典型的网络应用程序。我知道before_filter但考虑到我希望应用程序进入的方向,这似乎很麻烦。最终从任何

  5. ruby - 多个属性的 update_column 方法 - 2

    我有一个具有一些属性的模型:attr1、attr2和attr3。我需要在不执行回调和验证的情况下更新此属性。我找到了update_column方法,但我想同时更新三个属性。我需要这样的东西:update_columns({attr1:val1,attr2:val2,attr3:val3})代替update_column(attr1,val1)update_column(attr2,val2)update_column(attr3,val3) 最佳答案 您可以使用update_columns(attr1:val1,attr2:val2

  6. ruby - Infinity 和 NaN 的类型是什么? - 2

    我可以得到Infinity和NaNn=9.0/0#=>Infinityn.class#=>Floatm=0/0.0#=>NaNm.class#=>Float但是当我想直接访问Infinity或NaN时:Infinity#=>uninitializedconstantInfinity(NameError)NaN#=>uninitializedconstantNaN(NameError)什么是Infinity和NaN?它们是对象、关键字还是其他东西? 最佳答案 您看到打印为Infinity和NaN的只是Float类的两个特殊实例的字符串

  7. ruby - 检查方法参数的类型 - 2

    我不确定传递给方法的对象的类型是否正确。我可能会将一个字符串传递给一个只能处理整数的函数。某种运行时保证怎么样?我看不到比以下更好的选择:defsomeFixNumMangler(input)raise"wrongtype:integerrequired"unlessinput.class==FixNumother_stuffend有更好的选择吗? 最佳答案 使用Kernel#Integer在使用之前转换输入的方法。当无法以任何合理的方式将输入转换为整数时,它将引发ArgumentError。defmy_method(number)

  8. ruby-on-rails - 在 ruby​​ .gemspec 文件中,如何指定依赖项的多个版本? - 2

    我正在尝试修改当前依赖于定义为activeresource的gem:s.add_dependency"activeresource","~>3.0"为了让gem与Rails4一起工作,我需要扩展依赖关系以与activeresource的版本3或4一起工作。我不想简单地添加以下内容,因为它可能会在以后引起问题:s.add_dependency"activeresource",">=3.0"有没有办法指定可接受版本的列表?~>3.0还是~>4.0? 最佳答案 根据thedocumentation,如果你想要3到4之间的所有版本,你可以这

  9. ruby - 如何验证 IO.copy_stream 是否成功 - 2

    这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下

  10. ruby - Ruby 有 `Pair` 数据类型吗? - 2

    有时我需要处理键/值数据。我不喜欢使用数组,因为它们在大小上没有限制(很容易不小心添加超过2个项目,而且您最终需要稍后验证大小)。此外,0和1的索引变成了魔数(MagicNumber),并且在传达含义方面做得很差(“当我说0时,我的意思是head...”)。散列也不合适,因为可能会不小心添加额外的条目。我写了下面的类来解决这个问题:classPairattr_accessor:head,:taildefinitialize(h,t)@head,@tail=h,tendend它工作得很好并且解决了问题,但我很想知道:Ruby标准库是否已经带有这样一个类? 最佳

随机推荐