从 uitableView 将数据存储在 NSdictionary 中



我有一个自定义的可编辑UITableview,我的问题是如何在点击提交按钮时将其值存储在NSDictionary中。我的桌子就像一个简单的注册表。

扩展我的评论:

如果我理解你,你想用表视图和字典将数据从UItableViewCell获取回viewController。

有两种主要方法可以执行此操作,您可以为单元格创建委托或在单元格上创建块。因此,一旦文本完成编辑,就使用新数据调用委托/块。然后让 vc 保存它

使用块:

MyTableViewCell.h

@interface MyTableViewCell : UITableViewCell
@property (nonatomic, copy) void (^nameChangedBlock)(NSString *name);
@end

MyTableViewCell.m

在类似 textfield didFinishEditing 中:

 - (void)textFieldDidFinishEditing:(UITextField *)textField {
   if (textField == self.nameTextfield) {
         self.nameChangedBlock(textField.text)
   } 
}

在带有表视图的视图控制器中,在数据源方法 cellforRow 中

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
 // Do your standard stuff create the cell and set data;
 // dequeueReusableCellWithIdentifier: blah blah
   cell.nameChangedBlock = ^{
        // Alex j thank you 
        [yourNSMutableDictionary setObject:yourobject forKey:yourkey];
   };
    return cell
 }

假设您引用了文本字段,只需执行以下操作:

[yourNSMutableDictionary setObject:yourobject forKey:yourkey];

编辑* 如果您想从 uitableView 单击中获取信息,请查看此链接 使用 UITableViewCell 作为按钮

与其将所有信息存储在点击提交按钮上,我建议将其存储在- (void)textFieldDidEndEditing:(UITextField *)textField,这是UITextField的委托方法。

如果您在UITextField中显示一个清除按钮(十字图标(,那么当用户点击清除按钮时,您必须从NSDictionary中清除特定行。为此,您必须添加,- (BOOL)textFieldShouldClear:(UITextField *)textField也是如此。

如果您使用的是UITextView则还要包含相应的委托。

这背后的原因是,

  • 您拥有实时的用户信息,这意味着您的表单中几乎没有字段,名字,姓氏,地址,出生日期等。当用户在名字字段中,当焦点(点击以更改(为姓氏(或任何其他字段(时,textFieldDidEndEditing将接到呼叫,您可以将名字保存到字典中。

  • 同时,如果您显示一个清晰的按钮,当用户在名字字段中点击它时,textFieldShouldClear将接到电话,名字将立即从字典中删除。

  • 如果您正在准备一份大型注册表(或任何其他表格(。例如,从用户那里获取 20 个值,如果不使用此方法,则用户信息将在表单中保持可见。因为您可以随时从字典中获取并显示特定值。


- (void)textFieldDidEndEditing:(UITextField *)textField {
    NSString *getKey = [self keyForTag:textField.tag];
    if(textField.text.length != 0) {
    [dictionary setValue:textField.text forKey:getKey]; }
}
- (BOOL)textFieldShouldClear:(UITextField *)textField {
   NSString *getKey = [self keyForTag:textField.tag];
   if([dictionary valueForKey:getKey]) {
   [dictionary removeValueForKey:getKey];}
}
- (NSString *)keyForTag:(NSInteger)tag {
    if(tag == 1) {
       return @"kFirstName";
    }
    else if(tag == 2) {
       return @"kLastName";
    }
    ...
}
- (NSString *)showValueForTag:(NSInteger)tag {
    return [dictionary valueForKey:[self keyForTag:tag]];
}

最新更新