![](/img/trans.png)
[英]How to get cell data from button pressed event (Custom tableview cell)
[英]How to get the data from custom tableview cell
我是Iphone应用开发人员的新手。 我遇到了一个问题。 我有表格视图,因为我在每一行中插入了文本字段。 我完成了UI部分。 但如何才能从我在tableview中的文本框获取值。 我创建了customCell类。 我不能全部使用IBOutlet。
这是我的代码:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[CustomCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell...
return cell;
}
您应该有一个dataSource(通常是NSMutableArray),该数据源(通常)包含每个单元格的值。 你应该能够得到你需要使用indexPath的值,例如
NSObject *object = [dataArray objectAtIndex:indexPath.row];
在上面的代码我假定为的tableView则dataSource是称为dataArray中的阵列。 我还假定它包含NSObject类型的对象(在现实世界的示例中通常不是这样,在这种情况下,它通常是NSDictionary之类的子类或自定义NSObject子类。
确保tableView已连接到它的dataSource。 连接(至少)是通过UITableView实例上的setDataSource:方法以及numberOfSectionsInTableView:和numberOfRowsInSection:委托方法完成的。
你的UITableViewCell子类一般不应该用来保存数据,如果以这种方式来使用它,你采取错误的做法。 以下站点应该是使用UITableView类的不错的介绍: http : //www.mobisoftinfotech.com/blog/iphone/introduction-to-table-view/
正如Schreurs已经解释的那样,您需要对viewController(以及UITableViewDataSource)实现UITextFieldDelegate协议,请查阅文档中的内容以了解更多关于它们的操作。 但这比在视图中具有不同的UITextField更棘手。
您必须考虑以下事实:当单元格离开表格视图的可见范围时,它将被释放或重新使用。 因此,例如,如果一个单元格1包含一个文本字段,请在其中写一些内容,然后滚动到单元格15,您可能会得到一个带有单元格1的文本字段及其内容的单元格。 如果您准备好要重复使用的单元格,请清空textField,您必须将数据保留在某个位置以将其重新输入到正确的单元格中。 毕竟,您要挠头的是textField正在调用您的委托(可能是viewController,所以您将不得不用一个数字来标记它们,您可以从中提取行号-即cell.textField.tag = indexPath .row + 100)。
因此,总而言之,您需要在viewController中添加类似的内容
- (void)textFieldDidEndEditing:(UITextField *)textField {
if ([textField.text length] > 0) {
NSUInteger row = textField.tag - 1;
[textFieldValues setObject:textField.text forKey:[NSNumber numberWithInt:row]];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellId = @"cellId";
TextFieldTableViewCell *cell = (TextFieldTableViewCell *) [tableView dequeueReusableCellWithIdentifier:cellId];
if (!cell)
cell = [[[TextFieldTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId] autorelease];
cell.textField.tag = indexPath.row + 1;
cell.textField.delegate = self;
NSString *value = [textFieldValues objectForKey:[NSNumber numberWithInt:indexPath.row]];
if (value)
cell.textField.text = value;
else
cell.textField.text = @"";
return cell;
}
然后在您的TextFieldTableViewCell.h中
@property (nonatomic, readonly) UITextField *textField;
最后在您的TextFieldTableViewCell.m中
@synthesize textField;
ps我在徘徊,当编辑textField离开可见的单元格区域时,会发生什么,并且它没有被重用或释放...给了我寒意! 因此EndEditing应该足够了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.