【问题标题】:Objective C - UITextField Live Search an NSMutableArray and Output to UITableViewObjective C - UITextField 实时搜索 NSMutableArray 并输出到 UITableView
【发布时间】:2015-08-29 18:50:01
【问题描述】:

类似于 WhatsApp 向新群组添加参与者的功能,在我的应用中,我有一个 UITextField,用户可以在其中开始搜索也安装了应用以添加到群组聊天的联系人。

我使用以下键将所有可用联系人存储在 NSMutableArray searchableContacts 中

“名字” “姓” “电话号码”

使用以下委托方法,我想检查 UITextField 中的当前输入,看看它是否与 searchableContacts 数组中的 firstName 或 lastName 的任何一部分匹配:

-(void)textFieldDidChange :(UITextField *)theTextField{

    // Check if the user input matches the beginning of either firstName or lastName in contactsArray. If so, output that user information to the tableView

}

【问题讨论】:

    标签: objective-c uitextfield nsmutablearray


    【解决方案1】:

    您可以使用 NSPredicate 来过滤数组。

    例如这样:

    NSArray *users = @[
        [[User alloc] initWithFirstName:@"Test" lastName:@"Me"],
        [[User alloc] initWithFirstName:@"Fooo" lastName:@"bar"]
    ];
    
    NSString *searchTerm = @"bar";
    NSArray *filteredArray = [users filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(User *user, NSDictionary *bindings) {
        return [user.firstName containsString:searchTerm] || [user.lastName containsString:searchTerm];
    }]];
    
    NSLog(@"Filtered values: %@", filteredArray);
    

    在您的情况下,searchTerm 将是 theTextField.text 属性值。过滤后的数组包含所有匹配的联系人。

    干杯

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-23
      • 1970-01-01
      • 2011-12-13
      • 1970-01-01
      • 1970-01-01
      • 2013-02-20
      • 2018-01-18
      相关资源
      最近更新 更多