Victor Amaro Victor Amaro - 1 month ago 20
Swift Question

Tip Calculator - Swift

I'm just starting out in Swift, and wanted to make a tip calculator. But I'm running into some issues and was hoping someone could point me in the right direction. In the

getBillAmt
function, my total isn't updating/displaying, it only displays the
billAmt
I've tried a a few different options to get the total to update, but can't get it. My most recent attempt in below.

In my previous attempts my issues were not being able to convert Int to Float.

Variables,

var tipPercentAmt = Int()


var billAmt = Float() //bill before tip


var total = Float()


Slider, where user can slide to a tip amount (as an int)

@IBAction func tipAmtVal(sender: UISlider) {
let tipPercentAmt = Int(sender.value)
}


And, getting the bill amount from the user, from a text field (as a float) and then adding the tip to it to display the total in a label

@IBAction func getBillAmt(sender: UITextField) {
let billAmt = Float(billAmtText.text!)
let total = billAmt! + (Float(tipPercentAmt / 100)
tipAmtLabel.text = "\(total)"
}

//cause labels to update when user hits return
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}

Answer

Nothing is setup to actually call your getBillAmt function. Assuming your text field is setup properly with its delegate, the textFieldShouldReturn function will be called and that's it.

You need to call your getBillAmount from there.

func getBillAmt(textField: UITextField) {
    if let text = textField.text {
        if let billAmt = Float(text) {
            let total = billAmt + (Float(tipPercentAmt / 100)
            tipAmtLabel.text = "\(total)"
        }
    }
}

//cause labels to update when user hits return
func textFieldShouldReturn(textField: UITextField) -> Bool {
    textField.resignFirstResponder()

    getBillAmt(textField: textField)

    return false
}

As you can see I've made some other fixes too.

Comments