iOS 在自定义中处理 didSelectRowAtIndexPath class

iOS handle didSelectRowAtIndexPath in custom class

我看到了如何在自定义 classes 中设置事件处理程序的方法。像这样:

@implementation CustomClassWithTable {
    void (^_cellHandler)(Cell *cell);
}

...

- (void)setCellHandler:(void (^)(Cell *))handler
{
    _cellHandler = handler;
}

...

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ... 
    if (_cellHandler) {
        _cellHandler(cell);
    }
}

然后在控制器中它只需要设置 cellHandler 就可以了。我喜欢。首先,这种方法(模式)的名称是什么?其次,我如何在 swift 中执行此操作?这是最好的方法吗?假设我的自定义 class(菜单)中有 table,我希望能够在我的视图控制器中获取选定的单元格。我应该使用这种方法还是其他方法(例如委托模式)?

您在上面的代码中所做的是使用 objective C 块进行委托。 Swift 有一个类似的功能,称为闭包。由于此块能够在运行时设置赌注,因此您还可以使用策略模式在选择 table 行时委托不同的行为。

var cellHandler : ((cell: Cell) -> Void)?

if let callback = cellHandler {
    callback(cell)
}