class HomeController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
private let cellId = "cellId"
override func viewDidLoad() {
super.viewDidLoad()
collectionView?.register(Cell.self, forCellWithReuseIdentifier: cellId)
collectionView?.backgroundColor = UIColor.red
}
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 3
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! Cell
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 150, height: 150)
}
}
class Cell: UICollectionViewCell {
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setup() {
backgroundColor = UIColor.black
}
}
numberOfSections
and numberOfItemsInSection
are called (according to breakpoint), but cellForItemAt
and sizeForItemAt
are never called.
I don't see anything wrong?
UPDATE: (How I create HomeController in AppDelegate)
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
window?.makeKeyAndVisible()
let layout = UICollectionViewLayout()
let homeController = HomeController(collectionViewLayout: layout)
window?.rootViewController = UINavigationController(rootViewController: homeController)
return true
}
You are using UICollectionViewLayout()
You should use -
let layout = UICollectionViewFlowLayout()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With