SNos SNos - 1 year ago 184
iOS Question

Swift 2 - Protocol Delegate between two UICollectionViewControllers

I am trying to create a protocol delegate between two

. with the code I have I don't get any errors or warnings however, I cannot get the delegate to work. What am I missing?

Second Collection View

public protocol LettersCollectionViewDelegate: class {

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


class LettersCollectionView: UICollectionViewController {

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")



First Collection View

class AnswerCollectionView: UICollectionViewController {

let lettersView = LettersCollectionView()

override func viewDidLoad() {

self.lettersView.delegate = self



extension AnswerCollectionView: LettersCollectionViewDelegate {

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



enter image description here

Answer Source

You need your delegate to be the instance of the AnswerCollectionView that is embedded in your root view controller. Similarly, you need to set the delegate on the LettersCollectionView instance that is in the root view. let lettersView = LettersCollectionView() creates a new instance.

You can get the required references in prepareForSegue in your root view controller. You need to give the two embded segues in your storyboard identifiers, so you can identify them.

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download