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")
}
}