Swift 2 - 两个UICollectionViewControllers之间的协议委托

时间:2016-08-06 22:11:10

标签: ios delegates swift2 uicollectionview protocols

我正在尝试在两个UICollectionViewController之间创建协议委托。我有我的代码我没有得到任何错误或警告,但我不能让代表工作。我错过了什么?

第二个集合视图

    public protocol LettersCollectionViewDelegate: class {

        func DidSelectLetter(collectioView: UICollectionView,letter: Character, resultString:String)

    }

    class LettersCollectionView: UICollectionViewController {

        // DELEGATE
        weak var delegate: LettersCollectionViewDelegate?

    override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {

            let cell : UICollectionViewCell = collectionView.cellForItemAtIndexPath(indexPath)! as! LetterCellView



           delegate?.DidSelectLetter(collectionView, letter: "T", resultString:"TestString")

    }

}

第一次收藏视图

class AnswerCollectionView: UICollectionViewController {

   let lettersView = LettersCollectionView()

   override func viewDidLoad() {
        super.viewDidLoad()

        self.lettersView.delegate = self

    }

}

extension AnswerCollectionView: LettersCollectionViewDelegate {

    func DidSelectLetter(collectioView: UICollectionView, letter: Character, resultString: String) {

        print(letter)
    }
}

更新

enter image description here

1 个答案:

答案 0 :(得分:1)

您需要将委托作为嵌入在根视图控制器中的AnswerCollectionView的实例。同样,您需要在根视图中的LettersCollectionView实例上设置委托。 let lettersView = LettersCollectionView()创建新实例

您可以在根视图控制器中的prepareForSegue中获取所需的引用。您需要在故事板标识符中提供两个嵌入的segue,以便识别它们。

class ViewController: UIViewController {
   var lettersView: LettersCollectionView?
   var answersView: AnswersCollectionView?

   override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
       if segue.identifier == "lettersSegue" {
           let lettersView = segue.destinationViewController as? LettersCollectionView
       } else if segue.identifier = "answersSegue" {
           let answersView = segue.destinationViewController as? AnswersCollectionView
       }

       self.lettersView?.delegate = self.answersView
}