Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

collectionView:layout:sizeForItemAt not called swift 4 iOS 11

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
}
like image 857
Van Du Tran Avatar asked Dec 24 '22 13:12

Van Du Tran


1 Answers

You are using UICollectionViewLayout()

You should use -

 let layout = UICollectionViewFlowLayout()
like image 80
Jack Avatar answered Jan 26 '23 00:01

Jack