I have added a UICollectionViewCell
to my storyboard, and I added a UILabel
to my UICollectionViewCell
in storyboard. I have created a cell registration using UICollectionView.CellRegistration
and have implemented the cellProvider
closure for the datasource which dequeue a collection view cell of type TapLabelCollectionViewCell
(I have subclassed the cell in my storyboard to this class).
In my TapLabelCollectionViewCell
, I am trying to set the tap gesture recogniser on the label, but the label appears nil, which I've connected using an @IBOutlet
. Why is this and how can I fix it?
My code :
// UI View Controller:
class TapGridViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
tapGridCollectionView.collectionViewLayout = createLayout()
configureDataSource()
applySnapshot()
}
func configureDataSource() {
let cellRegistration = UICollectionView.CellRegistration<TapLabelCollectionViewCell, CellItem>(handler: {
(cell: TapLabelCollectionViewCell, indexPath: IndexPath, item: CellItem) in
cell.taplabel.text = String(item.labelCount)
})
dataSource = UICollectionViewDiffableDataSource(collectionView: tapGridCollectionView, cellProvider: { (collectionView: UICollectionView, indexPath: IndexPath, item: CellItem) in
let cell = collectionView.dequeueConfiguredReusableCell(using: cellRegistration, for: indexPath, item: item)
cell.delegate = self
cell.index = indexPath.row
return cell
})
}
}
// UI Collection View Cell:
protocol TapLabelCollectionViewCellDelegate: AnyObject {
func incrementNumberOfTaps(index: Int)
}
class TapLabelCollectionViewCell: UICollectionViewCell {
@IBOutlet var taplabel: UILabel!
var delegate: TapLabelCollectionViewCellDelegate?
var index: Int!
static let identifier = "tapLabelCellIdentifier"
override init(frame: CGRect) {
super.init(frame: frame)
setUpTapGestureRecognizer()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
func setUpTapGestureRecognizer() {
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(incrementNumberOfTaps))
print("tap Label,", taplabel)
taplabel.addGestureRecognizer(tapGestureRecognizer)
}
@objc func incrementNumberOfTaps() {
delegate?.incrementNumberOfTaps(index: index)
}
}