How to create a function in which as the +/- buttons increase, the total cost of the product will increase? I wrote this kind of code but it doesn't count right
@IBOutlet weak var counterlbl: UILabel! // Counter label
@IBOutlet var costLbl: UILabel! // Price label
var counter = 1 //Counter which contains the value to increment or decrement(+/-)
let minusTap = UITapGestureRecognizer(target: self, action: #selector(minusImageTapped))
minusBtn.addGestureRecognizer(minusTap)
minusBtn.isUserInteractionEnabled = true
//custom UIstepper I used images
let plusTap = UITapGestureRecognizer(target: self, action: #selector(plusImageTapped))
plusBtn.addGestureRecognizer(plusTap)
plusBtn.isUserInteractionEnabled = true
//decrement
@objc func minusImageTapped () {
let price = costLbl.text
var priceInt = Int(price!)
if counter > 1{
counter -= 1
let totalPrice = priceInt! / counter
counterlbl.text = String(counter)
costLbl.text = String(totalPrice)
print("minus")
}
}
//increment
@objc func plusImageTapped() {
let price = costLbl.text
var priceInt = Int(price!)
counter += 1
let totalPrice = priceInt! * counter
counterlbl.text = String(counter)
costLbl.text = String(totalPrice)
print("Plus")
}
You are changing the cost per item each time...
Let's say you start with
counter = 1and yourcostLblhas a "5" as its text.You tap the plus image, and your code does this:
you then set
costLbl.text = "10"so, the next time you tap "plus"...
and you set
costLbl.text = "30"so, the next time you tap "plus"...
and you set
costLbl.text = "120"and on and on.
You need a CostPerItem label, and a TotalPrice label.
Then, each time through you get the same "Cost per Item" from the CostPerItem label, and display the result of
priceInt * counterin the TotalPrice label.One thing that may have helped you figure this out sooner would be to put your calculations in a single function... then call that function (with an indicator of "incrementing" or "decrementing"), so you aren't confused about the whole multiply or divide issue.
Take a look at this: