Reputation: 55635
I'm trying to create a UICollectionView
whose width/height and coordinates are defined using AutoLayout (using SnapKit). When using the default UICollectionView
constructor it fails with the following reason:
reason: 'UICollectionView must be initialized with a non-nil layout parameter'
The only constructor that allows a layout to be passed in, also requires a frame
, so I tried using CGRectZero
as the value for the frame
like so:
collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: layout)
I then used SnapKit
to setup the constraints like so:
collectionView?.snp_makeConstraints { make -> Void in
make.width.equalTo(view)
make.height.equalTo(300)
make.top.equalTo(someOtherView)
}
However, when doing so the UICollectionView
is never rendered. In fact, I do not see the data source being called at all.
Any thoughts on how to use AutoLayout with a UICollectionView
or what I might be doing wrong?
Upvotes: 3
Views: 2068
Reputation: 5159
This following code works just fine for me and I got a red and empty collection view.
Xcode 7 beta 4 - Swift 2.0 - AutoLayout syntax from iOS 9
override func viewDidLoad() {
super.viewDidLoad()
let collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: UICollectionViewLayout())
collectionView.translatesAutoresizingMaskIntoConstraints = false
collectionView.backgroundColor = UIColor.redColor()
self.view.addSubview(collectionView)
collectionView.widthAnchor.constraintEqualToAnchor(self.view.widthAnchor).active = true
collectionView.heightAnchor.constraintEqualToConstant(300).active = true
collectionView.topAnchor.constraintEqualToAnchor(self.view.topAnchor).active = true
}
I never used SnapKit
but I do know it. The syntax provided in my code is almost the same as in your example. So it is only a clue that something is wrong with SnapKit
or how you use it.
I hope this can help you somehow.
Upvotes: 7