从集合视图中的可重用单元格获取按钮点击(xib 文件) [英] Get button click from reusable cell in collection view (xib file)
问题描述
我创建了可重复使用的单元格,在 XIB 中包含一个用于集合的按钮.
I have created reusable cell with include a button in a XIB for a collection.
我可以在集合视图中更改标签和按钮的文本,但我无法获得点击事件.
I can change the text of labels and buttons in the collection view but i can't get on click event.
我尝试了以下选项:
一个.这在 UICollectionViewCell 中:不工作
a. This in UICollectionViewCell : Not working
class cellVC: UICollectionViewCell {
@IBOutlet weak var sampleLabel: UILabel!
@IBOutlet weak var buttonClicked: UIButton!
@IBAction func buttonTest(_ sender: Any) {
print("dsfsdf 111111")
}
}
B.我也试过:不工作
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
let cell : cellVC = collectionView.dequeueReusableCell(withReuseIdentifier: "cellVC", for: indexPath) as! cellVC
cell.sampleLabel. = "sample text"
cell.buttonClicked.tag = indexPath.row
cell.buttonClicked.addTarget(self, action: #selector(masterAction(sender:)), for: .touchUpInside)
cell.buttonClicked.backgroundColor = UIColor.cyan
return cell
}
func masterAction(_ sender: UIButton) {
print ("button click")
}
由于两种解决方案都不起作用,我该如何实现这一点.
As both solutions are not working, how do i achieve this.
谢谢
推荐答案
当按钮链接到文件所有者而不是您的单元格时,有时会发生这种情况.
This sometimes happen when the button is linked to the File's Owner instead of your cell.
右键单击IB中的按钮并检查引用插座是否正确,这应该是您的单元格而不是文件的所有者,如下图所示:
Right click on the button in IB and check if the referencing outlet is correct, this should be your cell and not the File's Owner like in the image below:
这篇关于从集合视图中的可重用单元格获取按钮点击(xib 文件)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!