0
votes

In my app, I have a UIButton that is pressed for both starting and stopping an event. I am currently trying to change the title of the UIButton and it's background image programmatically using the following IBAction:

    @IBAction func StartandStop(sender: AnyObject) {
    if StartandStop.titleLabel?.text  == "Start Flight" {
        StartandStop.setTitle("Stop Flight", forState: UIControlState.Normal)
        StartandStop.setImage(UIImage(named: "End"), forState: .Normal)
    }
    else if StartandStop.titleLabel?.text  == "Stop Flight" {
        StartandStop.setTitle("Start Flight", forState: UIControlState.Normal)
        StartandStop.setImage(UIImage(named: "Start"), forState: .Normal)
    }
}

My program starts like this:

enter image description here

However, after I press the button the first time it becomes this:

enter image description here

When I continue to press the button it remains in the second state. Why is my button doing this?

1

1 Answers

0
votes

Use func setBackgroundImage(_:, forState:) instead of func setImage(_:, forState:), in addition, I would use func titleForState(:) instead of titleLabel?.text.

@IBAction func StartandStop(sender: AnyObject) {
    let title = StartandStop.titleForState(UIControlState.Normal)
    if title? == "Start Flight" {
        StartandStop.setTitle("Stop Flight", forState: UIControlState.Normal)
        StartandStop.setBackgroundImage(UIImage(named: "End"), forState: .Normal)
    }
    else if title? == "Stop Flight" {
        StartandStop.setTitle("Start Flight", forState: UIControlState.Normal)
        StartandStop.setBackgroundImage(UIImage(named: "Start"), forState: .Normal)
    }
}