问题
i am developing an app that you could add items to the Cart from MenuVC, then you can go to CartVC to view what is on your cart and increase or decrease quantity of items to be ordered. I cant make quantity label to change, don't know if thats because i get quantity from an array? is it unmutable?
Thank you for your help
Here is my cell
import UIKit
class BasketCell: UITableViewCell {
@IBOutlet weak var quantityLabel: UILabel!
@IBOutlet weak var itemLabel: UILabel!
@IBOutlet weak var priceLabel: UILabel!
var buttonIncrease : ((UITableViewCell) -> Void)?
var buttonDecrease : ((UITableViewCell) -> Void)?
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
@IBAction func increaseQuantity(_ sender: Any) {
buttonIncrease?(self)
}
@IBAction func decreaseQuantity(_ sender: Any) {
buttonDecrease?(self)
}
here is my example 2d array which i append it from web service
var items =
[
["Cheeseburger","Pizza","Sprite","Redbull"],
["10 $","20 $","5 $","6 $"],
[1,1,2,1,2]
]
and here is my cellForRowAt @CartVC
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView1.dequeueReusableCell(withIdentifier: "basketCell", for: indexPath) as! BasketCell
cell.quantityLabel.text = String(items[2][indexPath.row] as! Int)
cell.buttonIncrease = { (cell) in
var quantity = self.items[2][indexPath.row] as! Int
quantity += 1
self.tableView1.reloadData()
}
cell.buttonDecrease = { (cell) in
var quantity = self.items[2][indexPath.row] as! Int
if quantity > 1 {
quantity -= 1
self.tableView1.reloadData()
}
}
cell.itemLabel.text = items[0][indexPath.row] as? String
cell.priceLabel.text = items[1][indexPath.row] as? String
return cell
}
回答1:
is it unmutable?
When you declare new variable by downcasting some element from array of Any
objects, you get copy of this element which has no reference to element from array.
For your case would be better if you have your custom model
struct Item: Codable { // if you get this data from web service, you can use `JSONDecoder` to decode `Data` to `Item`/`[Item]`
var title: String
var price: String // better: `var price: Int` and then when you need to get text just add `" $"`
var quantity: Int
}
then you can have your items
array as array of Item
objects
var items = [Item(title: "Cheeseburger", price: "10 $", quantity: 1), ...]
now you can get certain item from items
in cellForRowAt
as element from items
with index equal to indexPath.row
let item = items[indexPath.row]
cell.quantityLabel.text = String(item.quantity)
And when you need to change it's amount property
self.items[indexPath.row].quantity += 1
来源:https://stackoverflow.com/questions/53996781/quantity-of-products-in-cart-view-controller-with-buttons-each-on-a-tablevie