【问题标题】:UITableViewController didSelectRowAtIndexPath:(NSIndexPath *)indexPathUITableViewController didSelectRowAtIndexPath:(NSIndexPath *)indexPath
【发布时间】:2011-11-27 17:15:45
【问题描述】:

如何引用在 didSelectRowAtIndexPath:(NSIndexPath *)indexPath 方法中单击的单元格对象?

我有一个 UISplitViewController,在 MasterView 中我有一个表格,其中 cell.tag = sqlite 数据库中的主键的单元格(即表格是从 db 填充的)。我能够在上述方法中捕获点击事件,但是我看不到如何将单元格对象传入,或者我如何引用它以获取 cell.tag。最终,目标是通过 Master/Detail 委托将该 id 传递给详细视图,然后根据来自 Master 的 id 将数据加载到 DetailView。

感谢任何提示!

编辑:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

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

    // Configure the cell.
    cell.textLabel.text = NSLocalizedString(@"Detail", @"Detail");
    Entry *entry = [self.entries objectAtIndex:[indexPath row]];
    [[cell textLabel] setText:[NSString stringWithFormat:@"%@",entry.title]];
    cell.tag = entry.entryID;
    return cell;
}

【问题讨论】:

    标签: iphone ios cocoa-touch ipad


    【解决方案1】:

    因为你已经有了一个条目数组,你也可以这样写。

    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
        Entry *entry = [self.entries objectAtIndex:[indexPath row]];
    }
    

    我认为这比 cellForRowAtIndexPath 更受欢迎:因为

    • 您可以获得整个条目对象,而不仅仅是 ID。
    • 您可以使用非整数 ID,如字符串。
    • 您不依赖表格或单元格(解耦)。

    【讨论】:

    • 是的,这样更好。我假设我必须通过我并再次查询数据库,但如果我可以传递整个条目对象,那是最好的情况。谢谢!
    【解决方案2】:

    在didSelectRowAtIndexPath:

    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    }
    

    注意向表格询问cellForRowAtIndexPath: 是如何返回一个单元格的,而向控制器询问tableView:cellForRowAtIndexPath: 会运行委托方法。

    【讨论】:

    • 这是我需要的。谢谢!
    【解决方案3】:

    您可以使用cellForRowAtIndexPath 方法从NSIndexPath 中获取UITableViewCell。

    【讨论】:

    • 这实际上是我填充我感兴趣的单元格属性的地方。请参阅上面的编辑。您是说我可以从 didSelectRowAtIndexPath 方法内部调用该方法吗?
    【解决方案4】:

    你可以把所有的id保存在NSMutableArray中,然后通过这个方法传入另一个类..

    classInstanceName.IntVariableName=[[taskIdArray objectAtIndex:indexPath.row]intValue]

    【讨论】:

      猜你喜欢
      • 2012-07-29
      • 1970-01-01
      • 1970-01-01
      • 2011-05-06
      • 2012-05-25
      • 2012-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多