更新 UICollectionView 内的标签

Update label inside UICollectionView

我使用 UICollectionView 创建了这个当我单击 Add(+)Remove(-) 按钮时,我想更新标签。我怎样才能做到这一点?

MainViewController.swift

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

    if(collectionView == ProductCollectionView){
        let Productcell = self.ProductCollectionView.dequeueReusableCell(withReuseIdentifier:"ProductCollectionViewCell", for: indexPath) as! ProductCollectionViewCell

        Productcell.AddOrMinusLabel.text = "\(bestOfferProductCount[indexPath.row])"
        Productcell.ProdName.text = bestOfferProductName[indexPath.row]
        Productcell.ProdPrice.text = bestOfferProductPrice[indexPath.row]
        Productcell.ProdtOrgPrice.text = bestOfferProductOriginalPrice[indexPath.row]
        Productcell.ProdWeight.text = bestOfferProductWeight[indexPath.row]+" "+bestOfferProductUnit[indexPath.row]
        Productcell.ProductImage.setImageFromURl(stringImageUrl: bestOfferProductImage[indexPath.row])

        return Productcell
    }

}

ProductCollectionViewCell.swift

import UIKit

class ProductCollectionViewCell: UICollectionViewCell {

@IBOutlet weak var ProdPrice: UILabel!
@IBOutlet weak var ProdtOrgPrice: UILabel!
@IBOutlet weak var ProductImage: UIImageView!
@IBOutlet weak var ProdName: UILabel!
@IBOutlet weak var ProdWeight: UILabel!

}

有多种方法可以解决这个问题。

1。旧委托机制

当您使 Cell 出列时,您必须删除所有观察者,然后将 Target 从单元格添加到您的 ViewController 以获取带有发送者的加号和减号的 tapEvents。在你的被调用方方法中,你必须获取它的 superView(直到你到达 collectionViewCell 视图),然后从 UICollectoinView 请求该单元格的 itemIndex,并相应地更新你的视图和单元格和模型。

2。使用闭包

您可以在 Cell 中定义两个闭包,一个用于加号,一个用于减号,而不是将 Target 添加到您的 viewController,将目标添加到您的单元格并调用相应的闭包,每次您尝试return 一个单元格,设置这些闭包并相应地对其进行操作。

class CustomCell: UICollectionCell {
    var plusAction: (() -> Void)?
    var minusAction: (() -> Void)?
    @IBOutlet var counterLabel: UILabel!

    @IBAction plusTapped() {
        plusAction?()
    }

    @IBAction minusTapped() {
        minusAction?()
    }
}

并在您的 cellDequeue 方法中:

cellForItemAtIndexPath(/*...other parameters...*/) -> UICollectionCell {
    let cell = collectionView.dequeueCell(/*...other parameters...*/) as! CustomCell
    // other customizations
    // weak allocation in closure might not be needed here since closure reference is nullable on the other end, but i wrote it just in-case.
    cell.plusAction = { [weak weakCell = cell] in
        let counter = 0 // i said 0 for ex, You actually have to have them stored somewhere (even initial zeros) and fetch the actual value for this indexPath
        let newCounter = counter + 1
        // update your Model with newCounter
        weakCell?.counterLabel.text = "\(newCounter)"
    }

    cell.minusAction = { [weak weakCell = cell] in
        let counter = 0 // i said 0 for ex, You actually have to have them stored somewhere (even initial zeros) and fetch the actual value for this indexPath
        let newCounter = counter - 1
        // update your Model with newCounter
        weakCell?.counterLabel.text = "\(newCounter)"
    }
}

我说,总是在单元格内配置你的单元格数据class

import UIKit

class ProductCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var addOrMinusLabel: UILabel!
@IBOutlet weak var ProdPrice: UILabel!
@IBOutlet weak var ProdtOrgPrice: UILabel!
@IBOutlet weak var ProductImage: UIImageView!
@IBOutlet weak var ProdName: UILabel!
@IBOutlet weak var ProdWeight: UILabel!

var count = 1 {
    didSet{
        self.addOrMinusLabel.text = "\(count)"
    }
}


 func configureData(count: Int) {
    self.count = count
}

@IBAction func subtract(_ sender: UIButton) {
    self.count -= 1

}
@IBAction func add(_ sender: UIButton) {
    self.count += 1
}

}

并在您的视图控制器中

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

if(collectionView == ProductCollectionView){
    let Productcell = self.ProductCollectionView.dequeueReusableCell(withReuseIdentifier:"ProductCollectionViewCell", for: indexPath) as! ProductCollectionViewCell
    Productcell.configureData(count: (bestOfferProductCount[indexPath.row]))

   // do try to configure these below labels also within cell class 
    Productcell.ProdName.text = bestOfferProductName[indexPath.row]
    Productcell.ProdPrice.text = bestOfferProductPrice[indexPath.row]
    Productcell.ProdtOrgPrice.text = bestOfferProductOriginalPrice[indexPath.row]
    Productcell.ProdWeight.text = bestOfferProductWeight[indexPath.row]+" "+bestOfferProductUnit[indexPath.row]
    Productcell.ProductImage.setImageFromURl(stringImageUrl: bestOfferProductImage[indexPath.row])

    return Productcell
}

}

试试这个简单又清醒的方法

将此代码添加到您的 viewcontroller

@IBAction func onBtnPlusClick(_ sender : UIButton) {
    if let cell = sender.superview?.superview as? ProductCollectionViewCell {
        let indexPath = yourCollectionViewOutlet.indexPath(for: cell)
    //Do whatever you want or update your data model values
         yourCollectionViewOutlet.reloadData()
    }
}

@IBAction func onBtnMinusClick(_ sender : UIButton) {
        if let cell = sender.superview?.superview as? ProductCollectionViewCell {
            let indexPath = yourCollectionViewOutlet.indexPath(for: cell)
        //Do whatever you want or update your data model values
         yourCollectionViewOutlet.reloadData()
        }
    }

在您的cellForItemAt中将目标添加到按钮

btnPlus.addTarget(self, action: #selector(self. onBtnPlusClick(_:)), for: .touchUpInside) 
btnMinus.addTarget(self, action: #selector(self. onBtnPlusClick(_:)), for: .touchUpInside) 

ProductCollectionViewCell class

中添加两个按钮插座
@IBOutlet var btnPlus : UIButton!
@IBOutlet var btnMinus : UIButton!

就是这样,希望对你有帮助

我会使用协议来做到这一点, 将此添加到您的单元格 class 并将 IBAction 添加到 UIButton。

class ProductCollectionViewCell: UICollectionViewCell {

  @IBOutlet weak var ProdPrice: UILabel!
  @IBOutlet weak var ProdtOrgPrice: UILabel!
  @IBOutlet weak var ProductImage: UIImageView!
  @IBOutlet weak var ProdName: UILabel!
  @IBOutlet weak var ProdWeight: UILabel!

  weak open var delegate: ProductCollectionViewCellDelegate?

  @IBAction func btnIncrement(_ sender: UIButton)
  {
    if let d = self.delegate {
      d.didTapOnIncrement(cell: self)
    }
  }

  @IBAction func btnDecrement(_ sender: UIButton)
  {
    if let d = self.delegate {
      d.didTapOnDecrement(cell: self)
    }
  }
}

protocol ProductCollectionViewCellDelegate: NSObjectProtocol {
    func didTapOnIncrement(cell: ProductCollectionViewCell)
    func didTapOnDecrement(cell: ProductCollectionViewCell)
}

现在在你的 cellForItemAt 方法中,添加这一行 -\

cell.delegate = self

现在确认代表确认协议。在这个例子中,我想是你的 viewController.

extension ViewController: ProductCollectionViewCellDelegate {

  func didTapOnIncrement(cell: ProductCollectionViewCell) {
    //let indexPath = self.tableView.indexPath(for: cell)
    //You have the cell's instance here. You can also get the indexPath by delegate method.
    //You can add the increment-decrement logic here.
  }

  func didTapOnDecrement(cell: ProductCollectionViewCell) {
    //let indexPath = self.tableView.indexPath(for: cell)
    //You have the cell's instance here. You can also get the indexPath by delegate method.
    //You can add the increment-decrement logic here.
  }

}