Anton Platonov Anton Platonov - 29 days ago 10
Swift Question

start and pause buttons enabled/disabled swift

I am a beginner so I may not see obvious things at this point. So please, help. I need my startButton enabled again when pauseButton is pressed and vice versa. I cannot create a var that can be accessed by both

UIButton
functions though. What should I do? Here's part of my code:

@IBAction func Start(_ sender: AnyObject) {

let disableMyStartButton = sender as? UIButton
disableMyStartButton?.isEnabled = false

timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(ViewController.update), userInfo: nil, repeats: true)
}


@IBAction func pauseTimer(_ sender: AnyObject) {

timer.invalidate()

WarningLabel.text = "Paused"
}

Answer

You need to create Outlet of your buttons and use them in your methods.

@IBOutlet var btnStart: UIButton!
@IBOutlet var btnPause: UIButton!

@IBAction func start(_ sender: UIButton) {

    sender.isEnabled = false
    btnPause.isEnabled = true
    timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(ViewController.update), userInfo: nil, repeats: true)
}

@IBAction func pauseTimer(_ sender: UIButton) {

    sender.isEnabled = false
    btnStart.isEnabled = true
    timer.invalidate()
    WarningLabel.text = "Paused"
}

You can also done this thing using single action for buttons like this.

@IBAction func onStartOrPause(_ sender: UIButton) {

    if (sender == btnStart) {
        sender.isEnabled = false
        btnPause.isEnabled = true
        timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(ViewController.update), userInfo: nil, repeats: true)
    }
    else {
        sender.isEnabled = false
        btnStart.isEnabled = true
        timer.invalidate()
        WarningLabel.text = "Paused"
    }
}

Note: You can also make same thing using single button by changing title or image of it in the action.

Comments