Swift 3- How to get button in UICollectionViewCell work

前端 未结 6 743
夕颜
夕颜 2020-12-09 23:19

I am trying to implement an Edit button inside a cell.

Please refer to image:

What I done so far:

MainController:

class MainCo         


        
6条回答
  •  -上瘾入骨i
    2020-12-09 23:54

    You might want to use a tag for a simpler approach, but I always implement a delegate pattern in the case of buttons inside cells

    protocol MyCollectionViewCellDelegate: class {
        func button(wasPressedOnCell cell: MyCollectionViewCell)
    }
    class MyCollectionViewCell: UICollectionViewCell {
        weak var delegate: MyCollectionViewCellDelegate?
        var data: String = "DATA"
        @IBAction func buttonWasPressed(sender: UIButton){
            delegate?.button(wasPressedOnCell: self)
        }
    
    }
    class MainViewController: UIViewController, UICollectionViewDataSource {
        func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "reuse", for: indexPath) as! MyCollectionViewCell
            cell.delegate = self
            return cell
        }
    }
    extension MainViewController: MyCollectionViewCellDelegate{
        func button(wasPressedOnCell cell: MyCollectionViewCell) {
            //do what you want with the cell and data
        }
    }
    

    Using this method will allow you to have multiple buttons inside a cell. Use a different delegate method for each button

提交回复
热议问题