【问题标题】:How to retrieve the data on selection of a cell from a custom UITableview如何从自定义 UITableview 中检索有关选择单元格的数据
【发布时间】:2012-01-21 14:08:35
【问题描述】:

可能是个愚蠢的问题。

我有一个 UITableview,有多个单元格。在每个单元格中,我都显示了一些数据。我没有使用单元格的文本属性来显示数据。相反,我的单元格中有一个自定义标签,用于显示文本。 我的问题是: 当我单击单元格时,我需要从单元格中检索数据。我该怎么做。

if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];


    UILabel *CellTextlabel = [[UILabel alloc] init];
    CellTextlabel.tag = 222;
    [CellTextlabel setFrame:CGRectMake(40, 5, 200, 20)];
    [cell.contentView addSubview:CellTextlabel];
    [CellTextlabel release];
  }


UILabel *editCellTextlabel = (UILabel *)[cell.contentView viewWithTag:222];
editCellTextlabel.font = [UIFont boldSystemFontOfSize:18];
editCellTextlabel.text = contact.lastName;

【问题讨论】:

  • 发布你用来填充单元格的代码。

标签: iphone ios uitableview uilabel didselectrowatindexpath


【解决方案1】:

在你的 didSelectRowAtIndexPath 方法中,你可以这样做:

UITableViewCell *cell = (UITableViewCell *)[self.tableViecellForRowAtIndexPath:indexPath];         
UILabel *textLabel = (UILabel *)[cell viewWithTag:222];

现在您可以使用 textLabel.text 检索单元格的 UILabel 中的数据

【讨论】:

    【解决方案2】:

    您可以通过以下方式访问didSelectRowAtIndexPath: 中的该标签

    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    UILabel *myLabel = [cell.contentView viewWithTag:222];
    

    但可能值得一问,为什么要添加子标签而不是使用 textLabel 属性?你可以修改它的框架、设置等,然后你不必担心标签,因为这个属性默认暴露在UITableViewCell

    【讨论】:

    • 我只是遇到了一些问题,因为我的单元格中有更多内容要显示。而我作为初学者无法在不添加更多标签和按钮的情况下处理对齐部分,而不是使用单元格文本属性和附件视图等
    • 我将继承 UITableViewCell 并通过属性公开您的数据,而不是使用 viewWithTag - 这将使您的代码更具可读性。
    • 如果你有多个标签,我同意@deanWombourne,你应该继承 UITableViewCell 并在那里添加所有属性。可以在cells的init方法中初始化,在layoutSubviews中设置每个子视图的frame
    【解决方案3】:

    -tableView:didSelectRowAtIndexPath:方法中,可以从tableView的数组中获取数据:

    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
        id objectForCell = [self.myArray objectAtIndex:indexPath.row];
        //do what you want with the above data.
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-06
      • 1970-01-01
      • 2011-04-27
      • 1970-01-01
      相关资源
      最近更新 更多