2016-03-12 57 views
0

我在自己的应用程序中有一个窗体,存在于带有自定义单元格的UITableView之外。这些单元格可以包含UITextField,UISegmentedControlUISwitch。这是我此设置:带有自定义UITableViewCells的窗体

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
    return 5; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableViewInner cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
DetailTableViewCell *cell; 

    static NSString *MyIdentifier = @"MyIdentifier"; 
    DetailTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:MyIdentifier]; 

    if (cell == nil) 
    { 
     cell = [[DetailTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier]; 
    } 

    [cell setTextField:@"John Appleseed"]; 

    // or 

    [cell setSegment]; 
    [cell setSegmentIndex:1]; 

    // or 

    [cell setSwitch]; 
    [cell setSwitchEnabled:YES]; 

    return cell; 
} 

现在,当用户点击保存按钮,我需要获取所有信息,并init与它的模型,就像这样:

[[Restaurant alloc] initWithName:@"Name here" withNotifications:1 withFrequency:1 withDate:@"Date here" andWithDistance:@"Distance here"]; 

有什么最好和最干净的方式可能将所有这些输入转换为我模型中的数据?我觉得循环所有的单元格有点过分。

回答

1

像遍历所有单元格是有点洁癖

它不只是在上面:这是完全错误的。数据不在单元格中;它生活在数据中。模型,视图,控制器;细胞只是查看!它的工作是代表模型(数据)。应该没有什么可以循环,因此;你应该已经有数据作为数据。

现在,当用户点击保存按钮,我需要获取这些信息

其实,我会做的是捕捉信息,当用户进行改变。将文本字段,开关或分段控件设置为控件动作目标,以便向您发送一条消息,告诉您发生了某些事情(例如更改开关值,编辑文本等),然后捕获数据。

接下来的唯一问题就是:我收到来自控件的消息:表中的哪一行是?为了找到答案,走从控制层级,直到你走到单元格,然后问这个单元代表什么行的表:

UIView* v = sender; // the control 
do { 
    v = v.superview; 
} while (![v isKindOfClass: [UITableViewCell class]]); 
UITableViewCell* cell = (UITableViewCell*)v; 
NSIndexPath* ip = [self.tableView indexPathForCell:cell]; 
+0

实际代码例如:http: //www.apeth.com/iOSBook/ch21.html#_editable_content_in_table_items – matt

+0

我哈哈我也有说:我不太喜欢Save架构。用户不希望必须点击保存才能使其更改保持不变。他们希望他们的变化能够在他们做出自动保存时自动保存。这就是我的书籍例子的行为。 – matt

0

使用定制模块更简洁的方法。 DetailTableViewCell.h

typedef void (^ saveBlock_block_t)(WhateverYourReturnObjectType *obj); 

@interface DetailTableViewCell : UITableViewCell 
- (void)configureCell:(NSString *)textFieldVal 
       cellBlock:(saveBlock_block_t)cellBlock; 
@end 

DetailTableViewCell.m

@interface DetailTableViewCell() 
{ 
    @property (copy, nonatomic) saveBlock_block_t saveBlock; 
} 
@end 

@implementation DetailTableViewCell 

- (void)configureCell:(NSString *)textFieldVal 
       cellBlock:(saveBlock_block_t)cellBlock 
{ 
    [cell setTextField: textFieldVal]; 
    [self setSaveBlock:cellBlock]; 
} 

-(IBAction)saveButtonAction:(id)sender //Action on your save button 
{ 
self.cellBlock(obj); // Whatever object you want to return to class having your table object 
} 
@end 

然后从的cellForRowAtIndexPath称其为 - 在我的书中的这一部分

[cell configureCell:@"John Appleseed” 
     cellBlock:^(WhateverYourReturnObjectType *obj){ 

     //Do what you want to do with 'obj' which is returned by block instance in the cell 
}];