更新UICollectionView中的标签

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了更新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!

}
答案

我会使用协议,将其添加到您的单元格类并将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.
  }

}
另一答案

我说,总是在单元格类中配置您的单元格数据

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
}

}
另一答案

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

1.旧代表机制

当你将一个Cell出列时,你必须删除AllObservers,然后从单元格中将AddTarget移动到你的ViewController,以获得带有发送者的加号和减号的tap事件。在你的callee方法中,你必须获取它的superView(直到你到达collectionViewCell视图),然后从UICollectoinView询问该单元格的itemIndex,并相应地更新你的视图和单元格和模型。

2.使用闭包

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

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)"
    }
}
另一答案

试试这个简单的清醒

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类中添加两个按钮插座

@IBOutlet var btnPlus : UIButton!
@IBOutlet var btnMinus : UIButton!

就是这样,希望这有帮助

以上是关于更新UICollectionView中的标签的主要内容,如果未能解决你的问题,请参考以下文章

如何根据 UICollectionView 的部分以编程方式更新标签

Swift UICollectionView 在单击时更新单元格标签而不是实时更新

Swift - UICollectionView:如何在标题中自动布局标签间距

UICollectionView reloadData() 不会更新集合视图中的单元格

UICollectionView 中的 UILabel 重载

UICollectionView 的 cellForItemAtIndexPath 无法识别单个单元格帧