There are a few things you should do differently, but this works fine for me (pretty much just the code you posted):
class TestCollWithBtnsCollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
@IBAction func editButtonTapped() -> Void {
print("Hello Edit Button")
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
{
return CGSize(width: 200.0, height: 200.0)
}
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 8
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath)
cell.backgroundColor = .orange
// this is the WRONG way to do this...
// 1) the button is being added avery time a cell is reused
// 2) the button should be added to the cell.contentView (not the cell itself)
// 3) much better ways to track than setting the button .tag to the row
// 4) target for the button action is "self" - locks you into a bad structure
// however, this can help us debug the problem
let editButton = UIButton(frame: CGRect(x: 8, y: 41, width: 154, height: 37))
// I don't have an image, so I set a button title and background color
editButton.setTitle("\(indexPath.row)", for: .normal)
editButton.backgroundColor = .red
// editButton.setImage(UIImage(named: "background-1 (dragged).tiff"), for: UIControlState.normal)
editButton.addTarget(self, action: #selector(editButtonTapped), for: UIControlEvents.touchUpInside)
editButton.tag = indexPath.row
editButton.isUserInteractionEnabled = true
cell.addSubview(editButton)
return cell
}
}
If you can see your button in your collection view cells, then your code (assuming you have the cell being created correctly) should have worked.
The fact that you also have the line:
cell.bringSubview(toFront: editButton)
kinda makes me think you don't see the button... Possibly your Y
coordinate of 241
places it outside the cell frame?