无法识别的选择器发送到自定义UICollectionView按钮中的实例

时间:2016-12-27 15:20:52

标签: ios swift

我有一个自定义UICollectionViewCell,在单元格内有一个名为collectionViewButton的按钮。

  func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CustomCollectionViewCell


    cell.collectionViewButton.tag = indexPath.item
    cell.collectionViewButton.addTarget(self, action:#selector(CollectionViewController.collectionButtonAction(_:)), for: .touchUpInside)

    ...

}

调用函数:

func collectionButtonAction(_ sender: UIButton){
    ...
}

按下按钮时出现错误:

  

' [ProjectName.CustomCollectionViewCell collectionButtonAction:]:   无法识别的选择器发送到实例'出现。

CustomCollectionViewCell代码:

class CustomCollectionViewCell: UICollectionViewCell {

@IBOutlet weak var collectionViewButton: UIButton!

}

2 个答案:

答案 0 :(得分:0)

在单元格初始化方法中为collectionViewButton添加一个目标,并在属性中调用闭包,例如:

class CustomCollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var collectionViewButton: UIButton!
    var actionHandler: (() -> Void)?

    init() {
        super.init(frame: .zero)
        collectionViewButton.addTarget(self, action:#selector(buttonAction), for: .touchUpInside)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func buttonAction() {
        actionHandler?()
    }
}

在集合视图委托的cellForItemAt方法中设置所需的处理程序。

答案 1 :(得分:0)

更改以下行

cell.collectionViewButton.addTarget(self, action:#selector(CollectionViewController.collectionButtonAction(_:)), for: .touchUpInside)

cell.collectionViewButton.addTarget(self, action:#selector(self.collectionButtonAction(_:)), for: .touchUpInside)

尝试一次。