swift - 如何在协议(protocol)扩展中设置委托(delegate)

标签 swift swift2 protocols protocol-extension

我有多个显示相同类型单元格的 View Controller 。我想在这样的协议(protocol)扩展中设置委托(delegate):

class ProductsViewController: UIViewController, ProductShowcase {
    //other properties
    @IBOutlet weak var productCollectionView: UICollectionView!
    var dataSource: DataSource!

    override func viewDidLoad() {
        super.viewDidLoad()

        setupDataSource()

        setupCollectionView()
    }

    func didSelectProduct(product: Product) {
        print(product)
    }

    //other functions
}

protocol ProductShowcase: UICollectionViewDelegate {
    var dataSource: DataSource! { get set }
    var productCollectionView: UICollectionView! { get }

    func didSelectProduct(product: Product)
}

extension ProductShowcase {
    func setupCollectionView() {
        productCollectionView.registerClass(ProductCollectionViewCell.self, forCellWithReuseIdentifier: "productCell")
        productCollectionView.dataSource = dataSource
        print(self) //prints ProductsViewController
        productCollectionView.delegate = self // 
        print(productCollectionView.delegate) //prints optional ProductsViewController
    }
}

extension ProductShowcase {
    //this delegate method is not called
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        didSelectProduct(dataSource.dataObjects[indexPath.row])
    }
}

didSelectItemAtIndexPathProductsViewController 中实现时,它会被调用。有没有我遗漏了什么或者这是一种错误的方法?

最佳答案

这是一个 Objective-C 互操作性限制。您不能像您想要的那样在协议(protocol)扩展中实现具有可选功能的协议(protocol)(来自 Objective-C 类型 UIKit 控件的委托(delegate)和数据源等的协议(protocol))。您可以只使用如下协议(protocol)的默认实现:

// No, @objc in the front of protocol. (i.e. objc-type protocol)
protocol X {
}

关于swift - 如何在协议(protocol)扩展中设置委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36777600/

相关文章:

swift - Swift OOP 设计中,如何安排一个常用的类?

Swift:符合协议(protocol)的AnyClass变量

networking - 四层防火墙功能

ios - 修改过多字节的数据对象会导致 swift 应用程序崩溃

ios - Swift:声音输出和麦克风输入 |使用 AudioKit |

ios - 删除在 View 上绘制的线

swift - 从单元格到新 View Controller 的图像传输通常会加载错误的图像,有什么方法可以解决这个问题吗?

ios - Swift 面向协议(protocol)编程 : Can Protocol Extension Property Have Same Name As Base Class Property

swift - Swift 中的自定义启动 - 有没有办法以 'not' 初始化方法中的某些属性?

ios - Swift 框架二进制文件中的路径问题