Search code examples
uibuttonswift4ibactioniboutlet

Can you change state of an IBAction button outside of its closure? - Swift 4


This is definitely NOT a duplicate of Disable a Button. I went through that several times with no success. In fact, I don't remember seeing sender.enabled there at all. I found that code in the Apple Developer's Forum.

Can you refer to an IBAction button by the sender argument and change its state from other places in your code? Changing the state of a button within the IBAction closure looks like: sender.enabled = false OR sender.enabled = true But I'm trying to change its state from within another function.

I know that it is possible to can change the state of an IBOutlet button from inside a different function like this:

@IBOutlet weak var myButton: UIButton!  
// then elsewhere in your code, within a method implementation:  
myButton.enabled = false   

But is something like that possible with an IBAction button.


Solution

  • Yes, you can change status property when you want..

        @IBOutlet var BtnOne:UIButton!
        @IBOutlet var BtnTwo:UIButton!
    
        @IBAction func btnOnePressed (_ sender: Any) {
            print("BtnOne is disabled") 
            BtnOne.isEnabled = false // or true
            //you can call any func
            btnTwoPressed()
        }
    
        @IBAction func btnTwoPressed (_ sender: Any) {
            print("BtnOne is enabled")
            BtnOne.isEnabled = true
        }