問題描述
如何在 UITableView 中使用 dequeueReusableCellWithIdentifier 快速管理購物車? (How to manage shopping cart in UITableView with dequeueReusableCellWithIdentifier in swift?)
我的 self.totalPriceLabel 顯示所有商店產品的總價格。它工作正常但是我什麼時候滾動 cell
由於 dequeueReusableCellWithIdentifier
self.totalPriceLabel
得到不正確的值。我將值保存在存儲在 NSUserDefaults
中的數組中。
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) ‑> UITableViewCell {
var cell : CartCell? = tableView.dequeueReusableCellWithIdentifier("cartCell") as! CartCell!
if(cell == nil)
{
cell = CartCell(style: UITableViewCellStyle.Default, reuseIdentifier: "cartCell")
}
cell?.itemCount.layer.cornerRadius = 5
cell?.clipsToBounds = true
cell?.itemCount.layer.borderWidth = 1
cell?.itemCount.layer.borderColor = UIColor.blackColor().CGColor
cell?.itemMinus.tag = indexPath.row
cell?.itemPlus.tag = indexPath.row
cell?.itemDelete.tag = indexPath.row
let key = self.readArray[indexPath.row]
cell?.itemCount.text = String("\(key.allValues[0])")
let tupleVar = getProductNameFromCharacter(String("\(key.allKeys[0])"))
cell?.itemName.text = tupleVar.tempName
cell?.itemPrice.text = String("\(tupleVar.price)")
//Actual Logic
let tempCount = key.allValues[0] as! Double
let nextItemPrice = (cell!.itemPrice.text! as NSString).doubleValue * tempCount
self.totalPriceLabel.text = String("\((self.totalPriceLabel.text! as NSString).doubleValue + nextItemPrice)")
return cell!
}
問題:當滾動 cell
得到錯誤的值。for self.totalPriceLabel
.
self. totalPriceLabel.text = String("((self.totalPriceLabel.text! as NSString).doubleValue + nextItemPrice)")
如何獲取 cell
值熄滅屏幕?如何解決由於滾動導致的這個問題?
參考解法
方法 1:
cellForRowAtIndexpath is the wrong place to do that calculation. You are assuming that iOS will call this function once for each cell. This isn't the case. This function is called to display a single cell. It could very well get called multiple times for the same cell as you scroll up and down.
You should be updating that total when you add or remove items from the underlying data (self.readArray).
Also, add code to change the total when the quantity button is tapped.
If you want more specific help, post the entire controller.
(by Avijit Nagare、ryantxr)