Search code examples
iosswiftuicollectionviewuilabel

How to display label inside of a cells Content View?


I am a beginner to Swift and I am following a tutorial to create a UICollectionView. In the tutorial when he creates a cell there is no "Content View' subsection like there is for me in Xcode.

On my storyboard my label is inside a cell's "Content View".

I have a outlet to the label (myLabel) in a separate file CollectionViewCell.swift

class CollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var myLabel: UILabel!

}

under my pages view controller I have this code

 //COLLECTION VIEW CODE STARTS

    let messageArray = ["1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20"]

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

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

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

        cell.myLabel.text = messageArray[indexPath.item]

        return cell
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print(indexPath.item)
    }
    //COLLECTION VIEW CODE ENDS

Everything works as it should, except myLabel is not visible the running the app, but I see all 20 of the cells displayed. How do I configure this "Content View" so my label is displayed?


Solution

  • Maybe it’s a constraint issue.. check your constraints