【问题标题】:Use delegate method written in Objective-C in Swift code在 Swift 代码中使用用 Objective-C 编写的委托方法
【发布时间】:2016-02-16 22:46:30
【问题描述】:

我想在 Swift 中使用用 Objective-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
}

但我不知道为什么,但该函数没有被调用。我有什么问题吗?我就是想用这个函数获取被刷过的cell的indexPath。

【问题讨论】:

    标签: objective-c swift interop


    【解决方案1】:

    您应该首先在您的表格视图控制器中实现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
    }
    

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

    【讨论】:

    • 感谢您的回答!有用。但现在我用这个手势/swipeTableCell 函数设置了一个 detailTextLabel。不知道为什么,但它没有显示在单元格中。我认为它与tableView(MGSwipeTableCell)的子类有关。希望你能帮助我。
    • 我认为您在cellForRowAtIndexPath: 中创建单元格时应该更改单元格的样式。当前样式设置为.Subtitle,应该是.Default
    【解决方案2】:

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

    所以,你要找的签名是这样的:

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

    但话虽如此,您仍然需要添加协议一致性。如果你先这样做然后尝试写出这个方法,它应该会自动完成到 Swift 期望的样子。

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

    【讨论】:

    • 感谢您的回答!有用。但现在我用这个手势/swipeTableCell 函数设置了一个 detailTextLabel。不知道为什么,但它没有显示在单元格中。我认为它与tableView(MGSwipeTableCell)的子类有关。希望你能帮助我。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多