从自定义单元格iPhone中的textField获取值

我有一个表格视图中的自定义单元格,见下文。

在这里输入图像说明

我在自定义单元格中有两个textFields txt1和txt2,如下所示

在这里输入图像说明

我怎样才能访问我在每个文本字段中input的值,以便我可以将值添加到单独的数组…

“Addset”button将通过增加一个更多的集合来递增分组表的部分。

我的表格视图代码如下。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *cellID= @"catogoryCell"; CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:cellID]; if(cell==nil) { NSArray *nibObjects = [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:nil options:nil]; for(id currentObject in nibObjects) { if([currentObject isKindOfClass: [CustomCell class]]) { cell = (CustomCell *)currentObject; } } } //cell.txt1.text = @"0"; return cell; } 

谢谢所有..

单元格是可重用的,所以他们需要更持久的方式来保存他们的信息。

方法1:您可以将一些UITextField对象保存到数组中,以防您不想重复使用文本字段,而在cellForRowAtIndexPath您只需将文本字段设置为其单元格,例如:

 cell.txt1 = [textFieldsArray objectAtindex:indexPath.section*2]; cell.txt2 = [textFieldsArray objectAtindex:indexPath.section*2+1]; //txt1 and txt2 properties should have assign 

方法2 :如果你想重复使用文本字段,那么我build议使用带有可变字典的数组,每个字典保存一个单元格的“设置”。 文本字段将由自定义单元完全pipe理(例如:在附加到单元格的字典中的UIControlEventValueChanged事件update @“txt1”或@“txt2”值处)。

 ///somewhere in the initialization (in the class holding the tableview) contentArray = [[NSMutableArray alloc] init]; ///when adding a new cell (eg: inside the 'Add set' action) [contentArray addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:@"", @"txt1", @"", @"txt2", nil]]; //add a new cell to the table (the same way you do now when tapping 'Add set') - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ ... [cell attachDictionary:[contentArray objectAtIndex:indexPath.section]]; return cell; } ///anywhere where you'd like to access the values inserted inside a cell NSMutableDictionary *cell3Content = [contentArray objectAtIndex:3]; NSString *text1 = [cell3Content valueForKey:@"txt1"]; NSString *text2 = [cell3Content valueForKey:@"txt2"]; ///CustomCell.m -(id)initWithCoder:(NSCoder *)decoder{ self = [super initWithCoder:decoder]; if(!self) return nil; [txt1 addTarget:self action:@selector(txt1Changed:) forControlEvents:UIControlEventValueChanged]; [txt2 addTarget:self action:@selector(txt2Changed:) forControlEvents:UIControlEventValueChanged]; return self; } -(void)attachDictionary:(NSMutableDictionary *)dic{ contentDictionary = dic; txt1.text = [contentDictionary valueForKey:@"txt1"]; txt2.text = [contentDictionary valueForKey:@"txt2"]; } -(void)txt1Changed:(UITextField *)sender{ [contentDictionary setValue:txt1.text forKey:@"txt1"]; } 

当您在UITableViewCell子类中创buildIBOutlet连接时,将它们连接到文件所有者(viewController)中的属性,而不是视图本身。 这样你就可以从你的viewController(UItableViewDataSource)