我有一个自定义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!
}
答案 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)
尝试一次。