baileymiller2017
baileymiller2017

Reputation: 175

Cannot modify label cell in Custom collectionView with Swift 3

Here is the code i modify by another example , the collectionView controller works fine, but come to the code that modify the label in collectionCell "cell.myLabel.text = self.items[indexPath.item]" , I get the error info : "fatal error: unexpectedly found nil while unwrapping an Optional value " what the matter with the program ?

here is the collection view controller code :

import UIKit


class myViewController: UIViewController, UICollectionViewDataSource ,UICollectionViewDelegateFlowLayout, UICollectionViewDelegate {

    let leftAndRightPaddings: CGFloat = 80.0
    let numberOfItemsPerRow: CGFloat = 7.0
    let screenSize: CGRect = UIScreen.main.bounds
    private let cellReuseIdentifier = "collectionCell"

override func viewDidLoad() {
    super.viewDidLoad()
    let flowLayout = UICollectionViewFlowLayout()
    let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: flowLayout)
    collectionView.register(MyCollectionViewCell.self, forCellWithReuseIdentifier: cellReuseIdentifier)
    collectionView.delegate = self
    collectionView.dataSource = self
    collectionView.backgroundColor = UIColor.cyan

    self.view.addSubview(collectionView)
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


let reuseIdentifier = "collectionCell" // also enter this string as the cell identifier in the storyboard
var items = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48"]


// MARK: - UICollectionViewDataSource protocol

// tell the collection view how many cells to make
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return self.items.count
}

// make a cell for each cell index path
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    // get a reference to our storyboard cell
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath ) as! MyCollectionViewCell

    let k = indexPath.item
    print("item="+items[k])

    //cell.myLabel.text = "a"
    //cell.backgroundColor = UIColor.brown
    // Use the outlet in our custom class to get a reference to the UILabel in the cell
    cell.myLabel.text =  self.items[indexPath.item]
    //cell.backgroundColor = UIColor.cyan // make cell more visible in our example project

    return cell
}

// MARK: - UICollectionViewDelegate protocol

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        // handle tap events
        print("You selected cell #\(indexPath.item)!")
    }
}

my custom collection cell with only a label to display

here is the "collectionCell" code :

import UIKit

class MyCollectionViewCell: UICollectionViewCell {

@IBOutlet weak var myLabel: UILabel!

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

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

Upvotes: 1

Views: 917

Answers (2)

Kuralay Biehler
Kuralay Biehler

Reputation: 67

Here code for SWIFT 5 with 2 cells in the CollectionViewController

import UIKit

// this is your UILabel
@IBOutlet weak var labelCell: UILabel!

  override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! MatrixCollectionViewCell

        switch indexPath.row {
        case 0:
            cell.labelCell.text = " "
        case 1:
            cell.labelCell.text = " "
        default:
            break
        }

// make extention for your CollectionViewController


extension CollectionViewController: UICollectionViewDelegateFlowLayout {

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        
        let collectionCell = collectionView.frame.width / 2 - 20
        
        return CGSize(width: collectionCell, height: collectionCell)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
    }
}

Upvotes: 0

Nirav D
Nirav D

Reputation: 72410

Register UINib instead of MyCollectionViewCell class with your CollectionView instance.

It should be :

collectionView.register(UINib(nibName: "View2", bundle: nil), forCellWithReuseIdentifier: cellReuseIdentifier)

Instead of :

collectionView.register(MyCollectionViewCell.self, forCellWithReuseIdentifier: cellReuseIdentifier)

Upvotes: 1

Related Questions