OGeek|极客世界-中国程序员成长平台

标题: iOS:通过单元格上的按钮操作将对象传递给自定义 UITableViewCell 到 UIViewController [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 18:56
标题: iOS:通过单元格上的按钮操作将对象传递给自定义 UITableViewCell 到 UIViewController

我有一个自定义的 UITableViewCell,上面有一个按钮,IB 链接到一个名为:

- (IBAction)clickUseid)sender;

在这个函数中,我打算将一个对象从 UITableView 的数据源(NSMutableArray 中的一个对象)传递给下一个 UIViewController , 当用户点击 UITableViewCell 上的按钮时。

我在自定义UITableViewCell中设置了一个属性,像这样:

@property (nonatomic, retain) SomeObject *some_object;

UITableViewcellForRowAtIndexPath 函数中,我将对象传递给单元格:

MyCustomCell *cell = (MyCustomCell *)[tableView dequeueReusableCellWithIdentifier:identifier];
cell.some_object = [self.cellData objectAtIndex:indexPath.row];

此时我跟踪对象,它仍然在这里。但在 MyCustomCell 单元格中,该对象已消失并分配给 nil。因此,无法将该对象传递给下一个UIViewController

我错过了什么?



Best Answer-推荐答案


也许使用不同的方法会更好。您可以给每个单元格按钮一个标签。标签值可以是行索引路径。

您的 -tableView:cellForRowAtIndexPath: 方法可能包括以下内容:

MyCustomCell *cell = (MyCustomCell *)[tableView dequeueReusableCellWithIdentifier:identifier];
cell.button.tag = indexPath.row

您的 -clickUse: 方法可能如下所示:

- (IBAction)clickUseid)sender
{
    UIButton *button = (UIButton *)sender;
    SomeObject *object = [self.cellData objectAtIndex:button.tag];

    // do stuff with your object on click
}

关于iOS:通过单元格上的按钮操作将对象传递给自定义 UITableViewCell 到 UIViewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8908649/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4