2017-08-09 101 views
0

我有一個UICollectionView在我的項目中,我添加了在每個單元格中添加的項目的數量,並在UIBarButtonItem中顯示總數。但是,當我瀏覽視圖時,數字會不斷變化。我知道這個問題與收集和表格視圖重複使用單元有關,並且我已經做了大量的研究,但是我無法解決這個問題。重寫「prepareForUse()」也沒有幫助。如果我天真的話,我還是個初學者,所以請原諒我。提前致謝。通過UICollectionView滾動不斷更新值

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 
} 
+0

您試圖顯示一個欄按鈕標題在整個集合視圖中的項目總數? – jegadeesh

+0

@Bader Yusuf Serhan改變或重複有不同之處嗎? –

+0

請顯示收集視圖的更多代碼 – 3stud1ant3

回答

0

您需要致電trayButton標題更新collectionView(_:cellForItemAt:)方法以外的代碼。

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)" 
-1

使用for循環每次重新加載tableView時,都會從arrayOfOrders中添加數量的所有數值。這是唯一的方法。

0
for (index, element) in arrayOfOrders.enumerate() 
{ 
    if let quantity = element["quantity"] as? Int{ 
      totalQuantity += quantity 
     } 
    trayButton.title = "\(totalQuantity)" 
} 

這樣做。 (我沒有檢查這個,所以做一些調整,如果需要的話。)

+0

我的問題實際上是滾動的收集視圖:( –