You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

未使用DidSelectRowAtIndexPath,如何从UITableViewCell获取数据?

嘿,这个问题很常见,我来给你两个靠谱的解决方案~

方案一:直接从数据源获取(优先推荐)

既然你已经拿到了选中行的索引 indexPath.row,而且创建选择器时传入的 colorList 就是这个表格的数据源,那直接从数组里取对应位置的值是最稳妥的方式——毕竟单元格的内容本来就来自数据源,这种方法不仅高效,还能避免表格视图单元格复用带来的潜在问题。

修改你的代码如下:

[selection CreateTableview:colorList withSender:sender withTitle:@"Please Select" setCompletionBlock:^(int tag){
    NSLog(@"Tag--->%d",tag);
    NSInteger selectedRow = (long)indexPath.row;
    NSLog(@"Selected Row %ld", selectedRow);
    
    // 从数据源数组获取选中单元格的值
    id selectedCellValue = colorList[selectedRow];
    NSLog(@"Selected Value: %@", selectedCellValue);
    
    updated_lenses = tag;
    [self.tableview reloadData];
}];

方案二:从UITableViewCell实例中获取

如果因为某些场景你必须从单元格对象里读取值,那你需要先拿到对应的单元格实例。不过要注意:只有当前可见的单元格才能被成功获取(不可见的单元格会被表格视图回收复用,可能返回nil)。

假设你使用的 selection 对象内部持有这个弹出的表格视图(比如属性名为 selectionTableView),可以这样修改代码:

[selection CreateTableview:colorList withSender:sender withTitle:@"Please Select" setCompletionBlock:^(int tag){
    NSLog(@"Tag--->%d",tag);
    NSInteger selectedRow = (long)indexPath.row;
    NSLog(@"Selected Row %ld", selectedRow);
    
    // 构建选中行的indexPath(默认section为0,根据你的实际情况调整)
    NSIndexPath *selectedIndexPath = [NSIndexPath indexPathForRow:selectedRow inSection:0];
    // 获取对应的单元格
    UITableViewCell *selectedCell = [selection.selectionTableView cellForRowAtIndexPath:selectedIndexPath];
    
    if (selectedCell) {
        // 如果是系统默认单元格,取textLabel的文本
        NSString *cellText = selectedCell.textLabel.text;
        NSLog(@"Selected Cell Text: %@", cellText);
        
        // 如果是自定义单元格,强转为你的自定义Cell类,再读取对应属性
        // CustomTableViewCell *customCell = (CustomTableViewCell *)selectedCell;
        // NSString *customValue = customCell.yourCustomProperty;
    }
    
    updated_lenses = tag;
    [self.tableview reloadData];
}];

小贴士:尽量优先使用方案一,因为从数据源直接取值的可靠性更高,不会受单元格可见状态的影响。

内容的提问来源于stack exchange,提问作者Anil Pahadiya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:56:32