首页 > 解决方案 > 快速设置单元格委托会出错

问题描述

我正在尝试使用MGSwipeTableCell库来制作自定义滑动单元格。但是,cell.delegate = self一直给我错误说

“无法将‘AlarmTableViewController’类型的值分配给‘MGSwipeTableCellDelegate’类型?”

但即使我插入'as!MGSwipeTableCellDelegate' 它会产生致命错误:

在展开 Optional 值时意外发现 nil。

class AlarmTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let reuseIdentifier = "programmaticCell"
        var cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath) as! MGSwipeTableCell

        cell.textLabel!.text = "Title"
        cell.delegate = self as! MGSwipeTableCellDelegate //optional
        return cell
    }
}

在我的故事板中,我将单元格的自定义类设置为MGSwipeTableCell,并将其标识符设置为programmaticCell. 请帮我。tableView快把我逼疯了。

标签: swiftdelegatestableview

解决方案


您需要MGSwipeTableCellDelegate为您的班级添加代表。

class AlarmTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, MGSwipeTableCellDelegate 

你崩溃的原因是强制as!转换,而它为零。


推荐阅读