在swift中使用objective-c编写的委托方法

时间:2015-11-15 21:18:50

标签: objective-c swift interop

我想在Swift中使用Objecive-C编写的委托方法。该方法包含在MGSwipeTableCell框架(MGSwipeTableCell.h)中。

目标-C:

-(BOOL) swipeTableCell:(MGSwipeTableCell*) cell tappedButtonAtIndex:(NSInteger) index direction:(MGSwipeDirection)direction fromExpansion:(BOOL) fromExpansion;

我尝试将其转换为swift并使用该方法:

func swipeTableCell(cell:MGSwipeTableCell, index:Int,  direction:MGSwipeDirection, fromExpansion:Bool) -> Bool {

    return true
}

但我不知道为什么但这个功能没有被调用。我有什么不对吗?我只想用这个函数获取刷过单元格的indexPath。

2 个答案:

答案 0 :(得分:0)

您应首先在表视图控制器中实现MGSwipeTableCellDelegate协议。所以你可以写:

class TableViewController : UITableViewController, MGSwipeTableCellDelegate {
    ....
    ....
    ....
    func swipeTableCell(cell:MGSwipeTableCell, index:Int,  direction:MGSwipeDirection, fromExpansion:Bool) -> Bool {
        return true
    }
}

然后在cellForRowAtIndexPath:方法中创建单元格时,您应该像这样创建它:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
  {
    let reuseIdentifier = "cell"
    var cell = self.table.dequeueReusableCellWithIdentifier(reuseIdentifier) as! MGSwipeTableCell!
    if cell == nil {
      cell = MGSwipeTableCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: reuseIdentifier)
    }
    cell.delegate = self
    return cell
}

然后,您将能够跟踪何时调用滑动方法,因为您设置了单元委托属性。

答案 1 :(得分:0)

您尝试使用的库似乎尚未采用Objective-C nullability annotations,因此,作为对象的任何返回值或参数将被转换为Swift,作为隐式解包的选项(带有感叹号)

所以,您正在寻找的签名是:

func swipeTableCell(cell: MGSwipeTableCell!, tappedButtonAtIndex: Int, direction: MGSwipeDirection, fromExpansion: Bool) -> Bool

但话说回来,无论如何都需要添加协议一致性。如果你先这样做,那么尝试编写这个方法,它应该自动完成Swift预期的外观。

然后确保您实际上将单元格的delegate属性设置为实现此方法的任何对象。