3

同じ種類のセルを表示する複数のビュー コントローラーがあります。次のようなプロトコル拡張でデリゲートを設定したい:

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れると呼び出されます。私が見逃したものはありますか、それともこれは間違ったアプローチですか?

4

1 に答える 1

3

これは、Objective-C の相互運用性の制限です。必要に応じて、プロトコル拡張でオプション機能を使用してプロトコルを実装することはできません (Objective-C タイプの UIKit コントロールのデリゲートおよびデータソースなどからのプロトコル)。次のように記述されたプロトコルのみのデフォルト実装を持つことができます。

// No, @objc in the front of protocol. (i.e. objc-type protocol)
protocol X {
}
于 2016-11-04T12:59:16.717 に答える