Hi, I am using a standalone CollectionView object in a ViewController that has many other elements other than the collection view.
var testCV : UICollectionView!
in loadView:
let flowLayout = UICollectionViewFlowLayout()
let photoCollectionViewLayoutFrame = CGRect(x: 0, y: 0, width: scrollView.bounds.width, height: CGFloat(150))
testCV = UICollectionView(frame: photoCollectionViewLayoutFrame, collectionViewLayout: flowLayout)
Creating the object, and setting up its Flow Layout seems fine, and I am conforming to the respective Flow Layout, Data Source and Delegate protocols.
Setting the data source works as expected.
override func viewDidLoad() {
super.viewDidLoad()
testCV.delegate = self
testCV.dataSource = self
print(testCV)
// newListingForm.photoCollectionView!.delegate = self as UICollectionViewDelegate
// print(newListingForm.photoCollectionView?.delegate)
// newListingForm.photoCollectionView.dataSource = self
// print(newListingForm.photoCollectionView)
}
However, the delegate is nowhere to be found when I print out the CollectionView Object.
Optional(<UICollectionView: 0x7fd74b06b400; frame = (0 0; 0 150); clipsToBounds = YES; gestureRecognizers = <NSArray: 0x6000023ed3e0>; layer = <CALayer: 0x600002dcea80>; contentOffset: {0, 0}; contentSize: {0, 0}; adjustedContentInset: {0, 0, 0, 0}; layout: <UICollectionViewFlowLayout: 0x7fd749d26680>; dataSource: (null)>)
And when I debug, the delegate property is missing.
Am I using CollectionView wrong?
I tested in a test project, and it works (I get valid references for dataSource and delegate). But in my case, no loadView, so I initialise testVC in viewDidLoad.
Try to move
let flowLayout = UICollectionViewFlowLayout()
let photoCollectionViewLayoutFrame = CGRect(x: 0, y: 0, width: scrollView.bounds.width, height: CGFloat(150))
testCV = UICollectionView(frame: photoCollectionViewLayoutFrame, collectionViewLayout: flowLayout)
to viewDidLoad.
Why do you overload loadView() ? There are a lot of warnings in loadView() doc when doing so:
If you use Interface Builder to create your views and initialize the view controller, you must not override this method. You can override this method in order to create your views manually. If you choose to do so, assign the root view of your view hierarchy to the view property. The views you create should be unique instances and should not be shared with any other view controller object. Your custom implementation of this method should not call super. If you want to perform any additional initialization of your views, do so in the viewDidLoad()method.