Swift 中的自定义 UITableViewCell 委托模式 [英] Custom UITableViewCell delegate pattern in Swift

查看:26
本文介绍了Swift 中的自定义 UITableViewCell 委托模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Swift + Objective-C 问题中遇到了一个奇怪的问题.

I have a weird problem in a Swift + Objective-C problem.

我正在快速实现一个 UITableView 和一个带有委托的自定义单元格,但是一旦我的 UITableViewController 将我的单元格委托分配给自己,它就会使我的应用程序和 Xcode 崩溃.是的,每次我的应用程序崩溃时,Xcode 也会崩溃,无论如何,但这是另一个问题.

I'm implementing a UITableView and a custom cell with a delegate in swift, but as soon as my UITableViewController assign my cell delegate to self, it crash both my app and Xcode. Yeah each time I crash my app, Xcode crash too, no matter what, but this is another problem.

这是我牢房的一部分

enum NewsCellActionType: Int {  
    case Vote = 0
    case Comments
    case Time
}

protocol NewsCellDelegate {
    func newsCellDidSelectButton(cell: NewsCell, actionType: NewsCellActionType)
}

class NewsCell: UITableViewCell {



    var cellDelegate: NewsCellDelegate?

 func selectedAction(action: NewsCellActionType) {
        self.cellDelegate?.newsCellDidSelectButton(self, actionType: action)
    }
}

这是我在 UIViewController 中设置委托的地方

And here is where I set the delegate in my UIViewController

 override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
        var cell = tableView.dequeueReusableCellWithIdentifier(NewsCellsId) as NewsCell
        if cell == nil {
            cell = NewsCell(style: UITableViewCellStyle.Default, reuseIdentifier: NewsCellsId)
        }
        cell.post = self.posts[indexPath.row] as HNPost
        cell.cellDelegate = self
        return cell

    }

它在 cell.cellDelegate = self 行崩溃,我不知道为什么.是当前 DP 的 bug,还是我做错了?

It crash at the line cell.cellDelegate = self, I have no idea why. Is it a bug in the current DP, or am I doing it wrong?

我尝试在我的委托 var + 协议上的 @objc 标记上使用弱,但由于我使用的是纯 Swift 枚举,所以我不能这样做.但我需要它吗?

I tried to use weak on my delegate var + the @objc tag on the protocol, but as I use a pure Swift enum I can't do that. But do I need it?

谢谢!

推荐答案

我在这里发布了答案.

目前,如果委托应该是 Objective-C 类的对象(如 UITableViewController),则必须使用 @objc 显式标记您的协议:

Currently you have to explicitly mark your protocols with @objc if the delegate should be an Object of a Objective-C class (Like the UITableViewController):

@objc protocol SwiftProtocol

这将使与 Objective-C 的互操作成为可能

This will enable interoperating with Objective-C

这篇关于Swift 中的自定义 UITableViewCell 委托模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆