自定义类中的iOS句柄DidSelectRowatineXpath
我已经看到了一种在自定义类中设置事件处理程序的方法。大概是这样的:自定义类中的iOS句柄DidSelectRowatineXpath,ios,objective-c,swift,delegates,event-handling,Ios,Objective C,Swift,Delegates,Event Handling,我已经看到了一种在自定义类中设置事件处理程序的方法。大概是这样的: @implementation CustomClassWithTable { void (^_cellHandler)(Cell *cell); } ... - (void)setCellHandler:(void (^)(Cell *))handler { _cellHandler = handler; } ... - (void)tableView:(UITableView *)tableView d
@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中做到这一点?这是最好的办法吗?假设我的自定义类(菜单)中有一个表,我希望能够在视图控制器中获取选定的单元格。我应该使用此代理还是其他方式(例如委托模式) 在上面的代码中,您所做的是使用objective C块进行委派。Swift有一个类似的特性,称为闭包。由于此块具有在运行时设置下注的功能,因此在选择表行时,也可以使用策略模式来委托不同的行为
var cellHandler : ((cell: Cell) -> Void)?
if let callback = cellHandler {
callback(cell)
}