How to set delegate in a protocol extension

我只是一个虾纸丫 提交于 2019-12-10 23:07:06

问题


I have multiple view controllers which shows same kind of cells. I want to set delegate in a protocol extension like this:

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

When didSelectItemAtIndexPath is implemented in ProductsViewController it gets called. Is there something I missed or is this a wrong approach?


回答1:


It is a Objective-C interoperability limitation. You are not allowed to implement protocols with optionals function in protocol extension like you wanted (protocols which are from Objective-C type UIKit control's delegates and datasources, etc.). You can have default implementation of only protocol that are written like:

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


来源:https://stackoverflow.com/questions/36777600/how-to-set-delegate-in-a-protocol-extension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!