How do you create a UICollectionView and add it to a ViewController programatically?

时间:2018-03-22 23:44:49

标签: ios swift uicollectionview constraints

I am trying to create a UICollectionView and adding it to a ViewController view but I can't get it to work.

import UIKit

class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {

    private let cellId = "cellId"

    lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewLayout()
        let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
        cv.dataSource = self
        cv.delegate = self
        cv.backgroundColor = .white
        cv.register(UICollectionViewCell.self, forCellWithReuseIdentifier: cellId)
        cv.translatesAutoresizingMaskIntoConstraints = false
        return cv
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        view.addSubview(collectionView)
        collectionView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
        collectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
        collectionView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
        collectionView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true

    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 15
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath)
        cell.backgroundColor = .red
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: view.frame.width, height: 50)
    }

}

In AppDelegate I set the window?.rootViewController like this:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.

    window = UIWindow(frame: UIScreen.main.bounds)
    window?.makeKeyAndVisible()

    let viewController = ViewController()
    window?.rootViewController = viewController

    return true
}

I get a black screen because I have not set the background of the ViewController view. But that should not matter because I have anchored the UICollectionView to the ViewController view, but still does not show.

What am I doing wrong?

1 个答案:

答案 0 :(得分:0)

Currently you are returning 15 as number of sections with a zero number of rows so , Add implementation for

 func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int

Also replace line

  let layout = UICollectionViewLayout()

with

 let layout = UICollectionViewFlowLayout()