Swift 3:collectionview上的按钮

Swift 3:collectionview上的按钮,swift,button,uicollectionview,swift3,uicollectionviewcell,Swift,Button,Uicollectionview,Swift3,Uicollectionviewcell,我在UICollectionView的原型单元格中添加了一个按钮,我想更新单元格标签中显示的属性: 谢谢,非常感谢 编辑: 可能需要创建一个同时获取indexPath.row的函数,但不知道如何实现 override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { //let cell

我在UICollectionView的原型单元格中添加了一个按钮,我想更新单元格标签中显示的属性:

谢谢,非常感谢

编辑: 可能需要创建一个同时获取indexPath.row的函数,但不知道如何实现

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

    // Configure the cell
    let myColor :UIColor = UIColor(red: 240/255, green: 179/255, blue: 28/255, alpha: 1.0)
    let presentCounter = counters[indexPath.row]
    cell.nameLabel.text = presentCounter.nameCD
    cell.valueLabel.text = String(presentCounter.valueCD)
    cell.backgroundColor = myColor
    cell.layer.cornerRadius=10

    return cell
}

@IBAction func masterCellAction() {

}

我认为您应该有以下两种解决方案:

  • 创建您自己的单元格类。这意味着该按钮将自行处理点击事件。通过这种方式,您需要创建一个新的UICollectionViewCell子类
  • 假设当用户选择单元格时(我的意思是用户可以点击单元格中的任何位置),您只需要实现didSelectAtCell函数,通过indexPath处理单元格

  • 希望对您有所帮助。

    在cellForItem上,将操作作为选择器添加到自定义按钮中,您将其添加到自定义单元格中,如下所示

    单元格?.customButton.addTarget(自身,操作:#选择器(masterCellAction),用于:。touchUpInside)

    编辑:


    您可以创建一个自定义类(例如CustomButton),该类继承UIButton并添加类型为NSIndexPath的indexPath属性。然后,将所有按钮设置为CustomButton类型,您就可以轻松地知道要更新的单元格

    如果需要的话,可以在masterCellAction中添加indexPath谢谢,但是我怎样才能在masterCellAction中添加indexPath呢?@IBAction func masterCellAction(indexPath:indexPath){}由于这是一个选择器,它知道从哪里获取indexPath,但是#选择器代码也将更改为#选择器(masterCellAction(:)或(:),首先更改func,自动完成将执行rest操作。在控制台“未识别的选择器发送到实例”中获取错误
    覆盖func collectionView(collectionView:UICollectionView,cellForItemAt indexPath:indexPath)->UICollectionViewCell{[…]cell.masterButton.addTarget(self,action:#选择器(主操作(indexPath:)),for:.touchUpInside)返回单元格}func主操作(indexPath:indexPath){let presentCounter=counters[indexPath.row]presentCounter.valueCD=presentCounter.valueCD+1}
    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
     cell.masterButton.addTarget(self,action: #selector(masterAction(_:)),for: .touchUpInside) 
    return cell 
    } 
    func masterAction(_ sender: UIButton) 
    { 
        let indexPath = collectionView?.indexPath(for: ((sender.superview?.superview) as! CounterCollectionViewCell))
    
    let presentCounter = counters[indexPath.row] presentCounter.valueCD = presentCounter.valueCD + 1 
    }