Reputation: 1859
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:
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?
I reproduced the error in this simple xcode project: https://github.com/Damnum/ReproduceControllerBug
Upvotes: 0
Views: 2015
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
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