ale00 ale00 - 1 month ago 7
Swift Question

Cannot see UILabel in a UICollectionViewCell added programmatically

I create a UICollectionViewCell programmatically when the user start a PanGesture on my CollectionView to reorder the cells (I don't use Apple APIs because I have to personalise the behaviour).

I create a Cell from a custom class

WordCollectionViewCell
that has an IBOutlet. Here is the code of the class:

class WordCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var wordLabel: UILabel!
}


To create the cell and add it to the CollectionView I use this code:

self.movingCell = {
let mC = WordCollectionViewCell(frame: selectedCell.frame)

// I HAVE TO DO THIS WITH A VARIABLE BECAUSE IF I ASSIGN UILabel() DIRECTLY TO mC.wordlabel, THE APP CRASH BECAUSE wordLabel IS NIL
let label = UILabel()
mC.wordLabel = label


mC.wordLabel.text = selectedCell.wordLabel.text
mC.addSubview(mC.wordLabel)

mC.backgroundColor = selectedCell.backgroundColor
mC.layer.cornerRadius = selectedCell.layer.cornerRadius
mC.tag = selectedIndexPath.row
return mC
}()

self.collectionView.addSubview(self.movingCell)

self.collectionView.addConstraint(NSLayoutConstraint(item: movingCell.wordLabel, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: movingCell, attribute: NSLayoutAttribute.top, multiplier: 1, constant: 0))
self.collectionView.addConstraint(NSLayoutConstraint(item: movingCell.wordLabel, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: movingCell, attribute: NSLayoutAttribute.bottom, multiplier: 1, constant: 0))
self.collectionView.addConstraint(NSLayoutConstraint(item: movingCell.wordLabel, attribute: NSLayoutAttribute.leading, relatedBy: NSLayoutRelation.equal, toItem: movingCell, attribute: NSLayoutAttribute.leading, multiplier: 1, constant: 0))
self.collectionView.addConstraint(NSLayoutConstraint(item: movingCell.wordLabel, attribute: NSLayoutAttribute.trailing, relatedBy: NSLayoutRelation.equal, toItem: movingCell, attribute: NSLayoutAttribute.trailing, multiplier: 1, constant: 0))


The Cell will follow the PanGesture location.

With this code there are two problems:


  1. I see nothing in
    movingCell
    testing on my device;

  2. Why I have can't set
    UILabel()
    directly to
    wordLabel
    ?


Answer

Try adding label.translatesAutoresizingMaskIntoConstraints = false