Speed Bird
Speed Bird

Reputation: 81

iOS - Swift 4 . - Updated UIButton label title not being used in function

I have the following code for a button label title (btnTD) which toggles its label title between "L" and "R" AFTER which it is meant to use the UPDATED Label title in a function called by another button's action (btnCalculate in this case).

Both the toggling of the label and the function called by btnCalculate work fine.

However, when I toggle the button, the function is using the button's title label BEFORE it is changed, not AFTER it is changed, even though the UI is showing the title toggling correctly.

It doesn't matter what order I put the toggling of the label or the function called by btnCalculate, the result is always the same.

    @IBAction func btnTD(_ sender: UIButton) {

    if btnTD.titleLabel!.text! == "R" {
        btnTD.setTitle("L", for: .normal)
    } else {
        btnTD.setTitle("R", for: .normal)
    }

    btnCalculate.sendActions(for: .touchUpInside)
}

Here is the code for btnCalculate.sendActions(for: .touchUpInside) although I don't think it is relevant

    @IBAction func btnCalculate(_ sender: UIButton) {
    txtOutput.text = Hold(IBTrk: Int(txtIBT.text!)!, TD: (btnTD.titleLabel!.text!) , OBTime: Double(txtOBTime.text!)!, TAS: Double(Int(txtTAS.text!)!), WD: Int(txtWD.text!)!, WS: Double(txtWS.text!)!)
}

Upvotes: 1

Views: 176

Answers (2)

Abdelahad Darwish
Abdelahad Darwish

Reputation: 6067

Just use btnTD.currentTitle Not tiltleLabel.Text

   @IBAction func btnCalculate(_ sender: UIButton) {
    txtOutput.text = Hold(IBTrk: Int(txtIBT.text!)!, TD: (btnTD.currentTitle) , OBTime: Double(txtOBTime.text!)!, TAS: Double(Int(txtTAS.text!)!), WD: Int(txtWD.text!)!, WS: Double(txtWS.text!)!)
}

Upvotes: 1

Chris
Chris

Reputation: 4391

Setting the button title does so for the .normal state. However the button is being pressed at this time so for a moment (while calculate function is called) its title is still the old value.

Using a global variable in the view controller is one way around this:

// Declare outside a method (in viewController)
var buttonState: String = "L" // Could also be a Bool variable

// Button action
@IBAction func btnTD(_ sender: UIButton) {
    if buttonState == "L" {
        buttonState = "R"
        btnTD.setTitle("R", for: .normal)
    } else {
        buttonState = "L"
        btnTD.setTitle("L", for: .normal)
    }
    // Then call the calculate method
    btnCalculate.sendActions(for: .touchUpInside)
}

Note: btnCalculate.sendActions() might be better as a separate function that is called here and also from btnCalculate button, rather than using sendActions.

Upvotes: 0

Related Questions