UICollectionView and AutoLayout
I am trying to create one UICollectionView
whose width / height and coordinates are defined with AutoLayout (using SnapKit). When using the UICollectionView
default constructor , this does not happen for the following reason:
reason: 'UICollectionView must be initialized with non-nil layout parameter'
The only constructor that allows you to pass the layout also requires frame
, so I tried to use CGRectZero
as a value for frame
so:
collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: layout)
Then I used SnapKit
to set restrictions like this:
collectionView?.snp_makeConstraints { make -> Void in
make.width.equalTo(view)
make.height.equalTo(300)
make.top.equalTo(someOtherView)
}
However, it is UICollectionView
never displayed. In fact, I don't see the data source being called at all.
Any thoughts on how to use AutoLayout with UICollectionView
or what I might be doing wrong?
This following code works fine for me and I got a red and empty collection.
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've never used it SnapKit
, but I know it. The syntax presented in my code is pretty much the same as in your example. So just a hint what something is wrong with SnapKit
or how you are using it.
Hope this can help you somehow.