【发布时间】: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])
}
}
当didSelectItemAtIndexPath 在ProductsViewController 中实现时,它会被调用。是我遗漏了什么还是这是一种错误的方法?
【问题讨论】:
-
我相信您遇到了此处描述的当前 Objective-C 互操作性限制:stackoverflow.com/questions/39487168/…
标签: swift swift2 protocols protocol-extension