0
votes

I have created Collection View with Collection View Cell. Inside Collection View Cell I have inserted UIButton. Now I can’t connect outlet because of error:

The firstPercent outlet from the ViewController to the UIButton is invalid. Outlets cannot be connected to repeating content.

How can I fix it?

1
You can't connect a button in a prototype cell to an IBOutlet in a UIViewController subclass - you have to connect it to an IBOutlet in a UICollectionviewCell subclass.Govind Kumawat

1 Answers

1
votes

It sounds like you are trying to connect the button to your ViewController, you cannot do this because the cell the button is in repeats. To connect the button you need to connect the button to a UICollectionViewCell class. I'll give you an example below on how to set up your cell.

class Cell: UICollectionViewCell {

     @IBOutlet var button: UIButton!

     override init(frame: CGRect) {
          super.init(frame: frame)
     }
     required init?(coder aDecoder: NSCoder) {
          fatalError("init(coder:) has not been implemented")
     }
}

Update per comment:

class ViewController: UIViewController {
    //other code
    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! Cell
        cell.button.addTarget(target: self, action: #selector(buttonTapped), for: .touchUpInside)

        return cell
    }

    @objc func buttonTapped() {
        print("do stuff here")
    }
}