获取tableView中的单元格值

Get cell value in tableView

我想通过以下方式获取 tableView 中的单元格值:

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

UITableViewCell *selectedCell=[tableView cellForRowAtIndexPath:indexPath];
NSLog(@"selected cell: %@", selectedCell);

}

它应该是一个字符串,但这是我在 NSLog 中得到的:

selected cell: <RewardCategoriesTableViewCell: 0x7ae11290; baseClass = UITableViewCell; frame = (0 92.01; 320 44); autoresize = W; layer = <CALayer: 0x7ae11450>>

这是我的数组数据源:

NSArray* data= [[NSArray alloc]initWithObjects:category1, category2, category3, category4, category5, category6, category7, nil];
return data;

这是cellForRowAtIndexPath:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

RewardCategoriesTableViewCell *cell = (RewardCategoriesTableViewCell*)[tableView dequeueReusableCellWithIdentifier:@"RewardCategoriesTableViewCell"];

if (cell == nil)
{
    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"RewardCategoriesTableViewCell" owner:self options:nil];
    cell = [nib objectAtIndex:0];
}

if(indexPath.section >= [categories count]){
    return nil;
}

Categories *category = [categories objectAtIndex:indexPath.section];

NSString *identifier = [NSString stringWithFormat:@"Cell%ld", indexPath.section];

NSLog(@"%@" , identifier);

cell.lblCategory.text = category.CategoryName;

NSLog(@"cell value: %@", cell.lblCategory.text);

return cell;
}

感谢您的帮助。

  • 按照您的方式,您会得到 UITableviewCellsubclass object,所以你记录的是对的。
  • 如果你想获取单元格值,你应该检查你的数据源,在 MVC 模式,即您的 Model.
  • 例如:你有一个名为dataArray的数组作为Model,那么你得到 值 dataArray[indexPath.row]

我不确定你为什么根据 indexPath.section 设置单元格文本,所以,我 post 示例代码基于你 post

的代码
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

  Categories *category = [categories objectAtIndex:indexPath.section];
  NSString * cellText = category.CategoryName;
}

BTY,我认为正确的方法是让单元格的文本基于行

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

RewardCategoriesTableViewCell *cell = (RewardCategoriesTableViewCell*)  [tableView dequeueReusableCellWithIdentifier:@"RewardCategoriesTableViewCell"];

if (cell == nil)
{
    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"RewardCategoriesTableViewCell" owner:self options:nil];
    cell = [nib objectAtIndex:0];
}

if(indexPath.row>= [categories count]){
    return nil;
}

Categories *category = [categories objectAtIndex:indexPath.row];

NSString *identifier = [NSString stringWithFormat:@"Cell%ld", indexPath.row];

NSLog(@"%@" , identifier);

cell.lblCategory.text = category.CategoryName;

NSLog(@"cell value: %@", cell.lblCategory.text);

return cell;
}

然后在:

  -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
  Categories *category = [categories objectAtIndex:indexPath.row];
  NSString * cellText = category.CategoryName;
}