【问题标题】:How to set delegate in a protocol extension如何在协议扩展中设置委托
【发布时间】:2016-04-21 18:24:33
【问题描述】:

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

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 中实现时,它会被调用。是我遗漏了什么还是这是一种错误的方法?

【问题讨论】:

标签: swift swift2 protocols protocol-extension


【解决方案1】:

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

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

【讨论】:

  • 把实现放在protocol ProductShowcase: UICollectionViewDelegate 会解决问题吗?我在哪里可以阅读有关此 Objective-C 互操作性限制的信息?另外,请注意,在 swift 3 中,我在该行得到 Segmentation Fault 11
  • 它不会解决你的问题。只有解决问题的方法是子类化。这里有一些限制:lynda.com/Swift-tutorials/Limitations-language-interoperability/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-05-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多