Hi Apple Dev Community,
I've searched both here and google for similar questions, but none of the answers I found actually helped me...
So bacically, I am trying to add subviews (in my case UICollectionView) programmatically, but when I do so, the delegate methods never get called.
Here is the code:
import UIKit
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
let myLayout = UICollectionViewFlowLayout()
collectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: myLayout)
collectionView.backgroundColor = UIColor.red
collectionView.delegate = self
view.addSubview(collectionView)
print("viewDidLoad")
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int)
-> Int {
print("numberOfItemsInSection")
return 50
}
// Initialize each cell
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath)
-> UICollectionViewCell {
print("cellForItemAt")
let myCell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath
as IndexPath)
myCell.backgroundColor = UIColor.blue
return myCell
}
}
As you can see, viewDidLoad is successfully called, but the deledate methods are never called.
Please notice how I explicitly set
collectionView.delegate = self
However, even that is not enough to get the delegate methods to fire. Clearly, I must be missing something.
Does anyone know how I can fix this code?
Thanks in advance!
KC