2016-04-21 10 views
1

Ich habe mehrere View-Controller, die die gleiche Art von Zellen zeigt. Ich möchte wie dies in einer Protokollerweiterung Delegierten setzen:So legen Sie Delegat in einer Protokollerweiterung fest

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]) 
    } 
} 

Wenn didSelectItemAtIndexPath in ProductsViewController implementiert wird es aufgerufen wird. Gibt es etwas, was ich vermisst habe oder ist das eine falsche Herangehensweise?

+0

Ich glaube, Sie in die aktuelle Objective-C Interoperabilität Einschränkung ausgeführt werden hier beschrieben: http://stackoverflow.com/questions/39487168/non-objc -method-does-not-satisfy-optional-Anforderung-of-objc-protocol/39604189 # 39604189 –

Antwort

1

Es ist eine Objective-C-Interoperabilitätsbeschränkung. Sie sind nicht berechtigt, Protokolle mit optionals Funktion in der Protokollerweiterung zu implementieren, wie Sie es wollten (Protokolle, die von Delegierten und Datenquellen des Objective-C-Typs UIKit Control stammen, usw.). Sie können Standardimplementierung von nur Protokoll haben, die geschrieben werden wie:

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

Putting die Implementierung in 'Protokoll ProductShowcase: UICollectionViewDelegate' wird das Problem lösen? Wo kann ich über diese Objective-C-Interoperabilitätsbeschränkung lesen? Beachten Sie auch, dass ich in swift 3 Segmentierung Fehler 11 auf dieser Zeile – osrl

+0

bekomme Es wird Ihr Problem nicht lösen. Der einzige Weg, um Ihr Problem zu lösen, ist die Unterklassenbildung. Hier einige Einschränkungen: https://www.lynda.com/Swift-tutorials/Limitations-language-interoperability/185037/367698-4.html?certificate=CE455E2C8E994AB398FA5E8CA22AC26B – Dari