【问题标题】:Scrolling through UICollectionView keeps on updating values滚动 UICollectionView 不断更新值
【发布时间】:2017-08-09 11:39:08
【问题描述】:

我的项目中有一个 UICollectionView,我在其中添加每个单元格中添加的项目数量,并在 UIBarButtonItem 中显示总数。但是,当我滚动浏览视图时,数字会不断变化。我知道这个问题与集合和表视图重用单元格的事实有关,我对此做了很多研究,但我无法解决这个问题。覆盖“prepareForUse()”也无济于事。我仍然是初学者,如果我天真,请原谅。提前致谢。

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = trayCell.dequeueReusableCell(withReuseIdentifier: "trayCell", for: indexPath) as! TrayItemCollectionViewCell

        //initializing labels

        if let quantity = arrayOfOrders[indexPath.row]["quantity"] as? Int{
            totalQuantity += quantity
            trayButton.title = "\(totalQuantity)"
        }

    return cell
}

【问题讨论】:

  • 您试图在条形按钮标题中显示整个集合视图中的项目总数?
  • @Bader Yusuf Serhan 有区别不断变化还是重复?
  • 请显示更多集合视图的代码
  • @jegadeesh 我的应用程序是餐厅菜单,您选择一组项目以及每个项目的数量,所以我试图显示总数量。它工作正常,但是当我向下或向上滚动时,值会随着单元格重新加载而不断变化
  • @TusharSharma 这个数字一直在增加,因为它每次都在增加

标签: ios xcode swift3 uicollectionview


【解决方案1】:

您需要在collectionView(_:cellForItemAt:) 方法之外调用trayButton 标题更新代码。

collectionView(_:cellForItemAt:) 将在每次出现单元格时被调用。理想的流程是在您获得 arrayOfOrders(可能在 viewDidLoad:)后立即使用以下代码更新该标题:

/// Get array of quantities
let quantityArray = arrayOfOrders.flatMap { $0["quantity"] as? Int }

/// Get sum
let totalQuantity = quantityArray.reduce(0, +)

/// Update button title
trayButton.title = "\(totalQuantity)"

【讨论】:

    【解决方案2】:
    for (index, element) in arrayOfOrders.enumerate()
    {
        if let quantity = element["quantity"] as? Int{
                totalQuantity += quantity  
            }
        trayButton.title = "\(totalQuantity)"
    }
    

    这样做。 (我没有检查这个,所以如果需要的话做一些调整。)

    【讨论】:

    • 我的问题实际上是与集合视图的滚动:(
    【解决方案3】:

    每次重新加载 tableView 时,使用 for 循环从 arrayOfOrders 添加所有数量的值。这是唯一的办法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      • 1970-01-01
      • 2011-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多