Swift:collectionviewcell 内的操作按钮

Swift: Action button inside a collectionviewcell

我在以编程方式创建的 collectionview 单元格中有一个按钮。

  @IBAction func editButtonTapped() -> Void {
        print("Hello Edit Button")

    }

j

 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

 let editButton = UIButton(frame: CGRect(x: 8, y: 241, width: 154, height: 37))
            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)
            cell.bringSubview(toFront: editButton)
}

但是当我点击按钮时,没有任何反应(它没有显示 "Hello Edit Button")。我错过了什么

集合视图正在捕获触摸事件并对其进行处理。您需要指定集合视图需要将触摸事件传递给它的子类。

override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {

    //loop through the cells, get each cell, and run this test on each cell
    //you need to define a proper loop
    for cell in cells {

         //if the touch was in the cell
         if cell.frame.contains(point) {
            //get the cells button
            for uiview in cell.subviews {
                if uiview is UIButton {
                   let button = uiview as! UIButton
                   //if the button received the touch, return it, if not, return the cell
                    if button.frame.contains(point) {
                       return button
                    }
                    else {
                       return cell
                    }
                 }
             }
         }
    }
    //after the loop, if it could not find the touch in one of the cells return the view you are on
    return view

}

有些事情您应该采取不同的做法,但这对我来说很好(几乎就是您发布的代码):

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
    }

}

如果您可以在您的集合视图单元格中看到您的按钮,那么您的代码(假设您正确创建了单元格)应该有效。

事实上你也有这条线:

cell.bringSubview(toFront: editButton)

有点让我觉得你没有看到按钮...可能你的 Y 坐标 241 将它放在单元格框架之外?