use delegate method written in objective-c in swift

限于喜欢 提交于 2021-02-08 10:19:14

问题


I'd like to use a delegate method written in Objecive-C in Swift. The method is included in the MGSwipeTableCell framework (MGSwipeTableCell.h).

Objective-C:

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

I try to convert it into swift to and use the method:

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

    return true
}

But I don't know why but the function isn't getting called. Did I something wrong? I just want to get the indexPath of the swiped cell with this function.


回答1:


You should implement MGSwipeTableCellDelegate protocol in your table view controller first. So you can just write:

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

and then when creating cells in cellForRowAtIndexPath: method you should create it like this:

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
}

Then you'll be able to track when swipe method is called because you set the cell delegate property.




回答2:


It appears that the library you're trying to use has not adopted Objective-C nullability annotations yet, as such, any return values or arguments which are objects will be translated into Swift as implicitly unwrapped optionals (with the exclamation mark).

So, the signature you're looking for is this:

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

But with that said, you need to add the protocol conformance anyway. If you do that first then try to write this method out, it should autocomplete to exactly how Swift expects it to look.

And then just make sure you're actually setting the cell's delegate property to whatever object is implement this method.



来源:https://stackoverflow.com/questions/33725173/use-delegate-method-written-in-objective-c-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!