Damnum
Damnum

Reputation: 1859

Cannot add collectionView outlet to UICollectionViewController in nib

I'm trying to instantiate a UICollectionViewController in the following fashion:

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        UINib(nibName: "TestController", bundle: nil).instantiateWithOwner(nil, options: nil)
    }
}

My nib is called TestController.xib and contains a UICollectionViewController containing a UICollectionView. When I add inside the nib an outlet collectionView from the UICollectionViewController to the UICollectionView, the line above throws the following error:

'NSInvalidArgumentException', reason: 'Can't add self as subview'

Probably there is a mistake in my thinking but I can't figure out why this error should happen.

Here is my nib:

enter image description here

EDIT:

When I don't add any outlet in my nib, the error disappears. But then the collectionView inside my UICollectionViewController is nil like so:

public class MyCollectionViewController: UICollectionViewController {

    override public func viewDidLoad() {
        super.viewDidLoad()

        //unwrapping error!
        self.collectionView!.backgroundColor = UIColor.blueColor() 
    }
} 

How can I fix this?

EDIT 2:

I reproduced the error in this simple xcode project: https://github.com/Damnum/ReproduceControllerBug

Upvotes: 0

Views: 2015

Answers (1)

Alex Curylo
Alex Curylo

Reputation: 4770

The reason this is happening is that although Interface Builder is displaying that controller as a UICollectionViewController, the internal magic link to collectionView is broken. Reasons for that include

  • It was created as a different controller type, and class was renamed to UICollectionView
  • It was created as a UICollectionView, but the class was edited to something else that IB recognized, then edited back
  • Something edited the XML source behind your back. Version control restore whilst actively editing perhaps?
  • IB crashed, got confused, or just felt cranky

But as people noted, in a correctly constructed nib collectionView absolutely will be populated at viewDidLoad time. So if it's not, I suggest dragging out a new controller instance and throwing this one away. That is almost certainly going to be quicker than trying to figure out exactly how and why the plumbing got broken on this one.

EDIT:

TIL that old school nib paradigms don’t work in Swift. Who knew? Not I, I'd only used storyboards since the dawn of Swift. How to correctly load a UICollectionView subclass as your main view without a storyboard is on Github here for those of you encountering the same issue.

Upvotes: 2

Related Questions