如何用按钮增加/减少价格标签值?

问题描述 投票:0回答:1

我有两个标签。第一个是quantityLabel,第二个是priceLabel。当我点击增加或减少按钮priceLabel增加或减少与quantityLabel值。 (例如1个数量是15,00美元2个数量是30,00美元)

我在下面试过

var quantity = 1
var updateFoodPrice: Double? {
    didSet {
        foodPrice.text = "\(Double(quantity) * updateFoodPrice!)"
    }
}

@IBAction func addQuantity(_ sender: Any) {
    if quantity < 30 {
        quantity += 1
        foodQuantity.text = String(quantity)

    }

}

@IBAction func decreasedQuantity(_ sender: Any) {
    if quantity > 0 {
        quantity -= 1
        foodQuantity.text = String(quantity)
        foodPrice.text? *= "\(quantity)"
    }
}

编辑:添加DetailVC与完整代码我的数据来自MainVC表视图选择单元格到DetailVc类DetailViewController:UIViewController {

@IBOutlet weak var foodTitle: UILabel!
@IBOutlet weak var foodSubTitle: UILabel!
@IBOutlet weak var foodPrice: UILabel!
@IBOutlet weak var drinkPicker: UITextField!
@IBOutlet weak var foodQuantity: UILabel!


var drinkPickerView = UIPickerView()
var selectDrinkType: [String] = []
var detailFoodName = ""
var detailFoodPrice = 0.0

var searchFoods: [String]!
var priceFood: [Double]!

let foods = Food(name: ["Hamburger big mac",
                           "Patates",
                           "Whopper",
                           "Steakhouse"], price: [15.0, 20.0, 25.0, 30.0])
let food: Food! = nil

var foodPriceCount = FoodPriceCount(quantity: 1, foodPrice: 15.0) {

    didSet {
        foodQuantity.text = "\(foodPriceCount.quantity)"
        foodPrice.text = "\(Double(foodPriceCount.quantity) * foodPriceCount.foodPrice)TL"

    }
  }

@IBAction func addQuantity(_ sender: Any) {
    if foodPriceCount.quantity < 30 {
        foodPriceCount.quantity += 1
    }
  }

@IBAction func decreasedQuantity(_ sender: Any) {
    if foodPriceCount.quantity > 0 {
        foodPriceCount.quantity -= 1
    }
    } 

viewDidLoad中()

   override func viewDidLoad() {
    super.viewDidLoad()

    foodQuantity.text = "1"

    searchFoods = foods.name
    priceFood = foods.price

    foodTitle.text = detailFoodName
    foodPrice.text = String(detailFoodPrice)
ios label swift4.2
1个回答
1
投票

addQuantity方法中,您不更新价格标签,在decreaseQuantity方法中,您不能使用标签的文本(字符串)并使用它进行数学运算。

我建议使用一个包含两个值的结构。使用结构的好处是不可变的。因此,每次更新其中的属性时,它都会创建结构的新实例。这样我们就可以使用didSet回调来在每次更改时更新标签。

Define a ViewModel struct

struct ViewModel {
    var quantity: Int
    var foodPrice: Double
}

Update the labels

var viewModel = ViewModel(quantity: 1, foodPrice: 10) {
    didSet {
        foodQuantityLabel.text = "\(viewModel.quantity)"
        foodPriceLabel.text = "\(Double(viewModel.quantity) * viewModel.foodPrice)"
    }
}

@IBAction func addQuantity(_ sender: Any) {
    if viewModel.quantity < 30 {
        viewModel.quantity += 1
    }
}

@IBAction func decreasedQuantity(_ sender: Any) {
    if viewModel.quantity > 0 {
        viewModel.quantity -= 1
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.