0

I have a IBOutlet declared and connected to InterfaceBuilder in my CubeController class like so:

// Class CubeController
    @IBOutlet weak var collectionView: UICollectionView!

Whenever I try to reference collectionView from another class, the collectionView is always an empty optional. This is my code:

// Another class
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) 
    {
       collectionView.performBatchUpdates
       ({
          print("selekt")
          let mug = CubeController()
          let colView = mug.collectionView
          if let _ = colView
          {
            print("uhu")
          }
         }, completion: {_ in
        })
    }

The "selekt" is printed, but "uhu" isn't. What's going on here? and What mistake did i do here?.The CubeController's collectionView outlet is working and displaying it self in user interface.How can i identify the mistake?

user3182143
  • 9,459
  • 3
  • 32
  • 39
potato
  • 4,479
  • 7
  • 42
  • 99
  • the view is not loaded when you create a view controller until you "present it", that's why the outlet is nil – tkanzakic Jul 17 '15 at 12:46

2 Answers2

0

A view controller's outlets are only hooked up when its view is loaded.

The problem is most likely that you're instantiating a new instance rather than using a reference to the existence instance of the view controller. If this is the case, you can find help here.

Although it may also be the very likely case that what you're doing is unnecessary. Why can't you use the collectionView parameter that you were passed in? Or at these definitely different collection views?

And finally, if you truly need a new instance, then you need to load the new view controller's view. This is done automatically if you present that view controller in some way, but you can force it with fooViewController.loadView(). I'm cautioning against this approach however because unless you're writing a unit test, this is almost certainly not what you need to be doing.

Community
  • 1
  • 1
nhgrif
  • 61,578
  • 25
  • 134
  • 173
  • There is no need for a new instance of view controller, in fact, the old one is preferable. About answer you provided: Not sure if I'm passing data.. and usage of singleton seems like an overkill. Really all I wanted was to be able to reference an outlet from a different view controller. – potato Jul 17 '15 at 13:14
  • Read all the answers to the question I linked, starting with my answer there. – nhgrif Jul 17 '15 at 13:15
  • Although best practice would argue that no other view controller should be accessing these outlets. – nhgrif Jul 17 '15 at 13:17
0
let mug = CubeController()
let colView = mug.collectionView

You just created a new CubeController instance, which isn't from your storyboard.

Oleg Shanyuk
  • 1,296
  • 2
  • 15
  • 26