我有多个视图控制器显示相同类型的单元格。我想设置代表在协议扩展这样的:如何设置代理协议扩展
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
实现它被调用。有什么我错过了,或者这是一个错误的方法?
我相信你正在运行到这里所描述的当前的Objective-C的互操作性的限制:http://stackoverflow.com/questions/39487168/non-objc -method-does-not-satisfy-optional-optional-requirement-of-objc-protocol/39604189#39604189 –