2016-04-21 83 views
1

我有多个视图控制器显示相同类型的单元格。我想设置代表在协议扩展这样的:如何设置代理协议扩展

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实现它被调用。有什么我错过了,或者这是一个错误的方法?

+0

我相信你正在运行到这里所描述的当前的Objective-C的互操作性的限制:http://stackoverflow.com/questions/39487168/non-objc -method-does-not-satisfy-optional-optional-requirement-of-objc-protocol/39604189#39604189 –

回答

1

这是一个Objective-C的互操作性限制。您不允许使用协议扩展中的optionals函数来实现协议(您需要的协议(来自Objective-C类型UIKit控件的委托和数据源等的协议)。你只能有协议的默认实现,它是这样写的:

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

把实现放在'protocol ProductShowcase:UICollectionViewDelegate'中会解决问题吗?我在哪里可以阅读有关Objective-C互操作性限制?此外,请注意,在迅速3我得到分段错误11在该行 – osrl

+0

它不会解决您的问题。只有解决你的问题的方法是继承。这里的一些限制:https://www.lynda.com/Swift-tutorials/Limitations-language-interoperability/185037/367698-4.html?certificate=CE455E2C8E994AB398FA5E8CA22AC26B – Dari