Swift 3- How to get button in UICollectionViewCell work

前端 未结 6 776
夕颜
夕颜 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条回答
  •  孤街浪徒
    2020-12-10 00:13

    I have created the same scenario. The only difference is that I have used UIButton instead of RaisedButton. And it is working perfectly fine.

    1.ImgItemCell

    class ImgItemCell: UICollectionViewCell
    {
        //MARK: View Lifecycle Methods
        override func awakeFromNib()
        {
            super.awakeFromNib()
            setupViews()
        }
    
        let editButton: UIButton = {
            let button = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 50))
            button.setTitle("Edit", for: .normal)
            return button
        }()
    
        func setupViews()
        {
            addSubview(editButton)
        }
    }
    

    2.MainController methods

    //MARK: UICollectionViewDataSource
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
    {
        return 10
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
    {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: imgCellId, for: indexPath) as! ImgItemCell
        cell.editButton.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside)
        return cell
    }
    
    @objc func buttonPressed()
    {
        print("buttonPressed !")
    }
    

提交回复
热议问题