简体   繁体   中英

How to make UICollectionView class programmatically in iOS Swift 3 without using storyboard?

I made a class GalleryCollectionViewController that inherited from UICollectionView like this:

import UIKit  

class GalleryCollectionViewController: UICollectionViewController {

var dataSourceArr:Array<UIImage>!
    override convenience init(collectionViewLayout layout: UICollectionViewLayout) {
        self.init()
        collectionView?.collectionViewLayout = layout
        collectionView!.register(GalleryCollectionViewCell.self, forCellWithReuseIdentifier: "cell")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }

   // MARK: UICollectionViewDataSource

    override func numberOfSections(in collectionView: UICollectionView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        if dataSourceArr.count != 0 {
            return dataSourceArr.count
        }
        return 0
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! GalleryCollectionViewCell

        cell.imageView.image = dataSourceArr[indexPath.row]

        return cell
    }  

GalleryCollectionViewCell has defined.

And in root controller set this in viewDidLoad :

let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 20, left: 10, bottom: 10, right: 10)
layout.itemSize = CGSize(width: 90, height: 120)
let galleryColVC = GalleryCollectionViewController(collectionViewLayout: layout)
galleryColVC.dataSourceArr = photoLibraryImagesArr
self.present(galleryColVC, animated: true, completion: nil)

And but get this error in UICollectionView :

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'UICollectionView must be initialized with a non-nil layout parameter'

Please help to fix this.

Here is small example

import UIKit

class ViewController: UIViewController {

  let cellId = "cellId"

  let newCollection: UICollectionView = {
     let layout = UICollectionViewFlowLayout()
     layout.scrollDirection = .horizontal
     let collection = UICollectionView(frame: CGRect(x: 0, y: 0, width: 0, height: 0), collectionViewLayout: layout)
     collection.translatesAutoresizingMaskIntoConstraints = false
     collection.backgroundColor = UIColor.darkGray
     collection.isScrollEnabled = true
    // collection.contentSize = CGSize(width: 2000 , height: 400)
     return collection
  }()

  override func viewDidLoad() {
      super.viewDidLoad()

      view.addSubview(newCollection)
      newCollection.delegate = self
      newCollection.dataSource = self
      newCollection.register(CustomeCell.self, forCellWithReuseIdentifier: cellId)
      setupCollection()
  }


  func setupCollection(){

      newCollection.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
      newCollection.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
      newCollection.heightAnchor.constraint(equalToConstant: 400).isActive = true
      newCollection.widthAnchor.constraint(equalToConstant: view.frame.width).isActive = true 
  }

}

extension ViewController: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
       return 100
    }


   func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
       let cell = newCollection.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! CustomeCell
       cell.backgroundColor = .white
       cell.layer.cornerRadius = 5
       cell.layer.borderWidth = 2
       cell.layer.borderColor = UIColor.white.cgColor
       cell.layer.shadowOpacity = 3
       return cell
   }

   func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

       return CGSize(width: 150, height: 250)
   }

   func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
       return UIEdgeInsets(top: 3, left: 3, bottom: 3, right: 3)
   }
}

class CustomeCell: UICollectionViewCell {

   override init(frame: CGRect) {
       super.init(frame: frame)
       setupViews()
   }

   required init?(coder aDecoder: NSCoder) {
       fatalError("init(coder:) has not been implemented")
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM