如何在协议扩展中设置委托

时间:2016-04-21 18:24:34

标签: swift swift2 protocols protocol-extension

我有多个视图控制器,显示相同类型的单元格。我想在这样的协议扩展中设置委托:

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])
    }
}

didSelectItemAtIndexPath中实施ProductsViewController时会调用它。有没有我错过的或这是一个错误的方法?

1 个答案:

答案 0 :(得分:2)

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

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