【问题标题】:Set cellDelegate using generic使用泛型设置 cellDelegate
【发布时间】:2017-02-22 10:10:05
【问题描述】:

大家好,你们好吗?希望你们一切都好。

我需要一点帮助,在此先感谢您。

我的自定义单元格中有一个自定义委托,如下所示:

protocol customTableViewCellDelegate: NSObjectProtocol {
    func buttonPressed(customCell: customTableViewCell)
} 

我有一个扩展来设置表格视图中的单元格,如下所示:

extension UITableView {
    func layoutTemplateCell<T: UIViewController>(indexPath: IndexPath, viewController: T.Type) -> UITableViewCell {
            let cell = UITableViewCell()

                switch template {
                case customCell:
                    let cell = self.dequeueReusableCell(withIdentifier: customTableViewCell.identifier) as! customTableViewCell
                    cell.delegate = viewController.self
                    return cell
                default:
                    break
                }
            return cell
        }
}

但我在 cell.delegate 中遇到错误“无法将 T.type 类型的值分配给 customTableViewCellDelegate 类型?”

我不知道如何正确使用泛型,也不知道如何修复此错误。

我希望你们能帮助我。感谢您抽出宝贵的时间阅读本文,祝您有美好的一天。

【问题讨论】:

    标签: ios swift uitableview generics swift3


    【解决方案1】:

    您正在尝试将视图控制器的类分配给委托属性,而不是视图控制器实例。你想要的是:

    cell.delegate = viewController
    

    我不明白你为什么要使用泛型。您可以只使用协议:

    protocol CustomTableViewCellDelegate: NSObjectProtocol {
        func buttonPressed(customCell: UITableViewCell)
    }
    
    extension UITableView {
        func layoutTemplateCell(indexPath: IndexPath, viewController: CustomTableViewCellDelegate) -> UITableViewCell {
                let cell = UITableViewCell()
    
                    switch template {
                    case customCell:
                        let cell = self.dequeueReusableCell(withIdentifier: customTableViewCell.identifier) as! CustomTableViewCell
                        cell.delegate = viewController
                        return cell
                    default:
                        break
                    }
                return cell
            }
    }
    

    【讨论】:

    • 嗨,我使用泛型是因为我想为扩展使用更多的一个 viewController。想象一下,所有拥有 tableView 的 viewController 都将使用相同的扩展。
    • 仍然没有必要使用泛型。布局功能无关紧要;它只需要知道它有符合协议的东西
    • 嗨,保罗,它之所以有效,是因为您正在使用像这样的一个视图控制器 func layoutTemplateCell(indexPath: IndexPath, viewController: CustomTableViewCellDelegate) -> UITableViewCell 但我想与多个视图控制器一起使用所以我必须做点像这样 func layoutTemplateCell(indexPath: IndexPath, viewController: UIViewController) -> UITableViewCell 当我这样做时我有同样的错误
    • 不,您传递给此函数的任何视图控制器必须符合协议。如果您想使用 UIViewController 作为参数类型,那么您可以有条件地向下转换为CustomTableViewCellDelegate,并且只分配向下转换的委托属性成功。您在这里尝试做的任何事情都不需要泛型。
    • Paul 谢谢你,我理解你所说的并更改我的代码,将演员表放在代表身上并工作!非常感谢!!
    猜你喜欢
    • 1970-01-01
    • 2021-01-21
    • 2021-11-11
    • 1970-01-01
    • 1970-01-01
    • 2013-04-07
    • 2020-08-06
    • 1970-01-01
    • 2011-02-28
    相关资源
    最近更新 更多