Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Auto call an @IBAction function

Tags:

ios

swift

Hi I am not sure how to do auto call a click-function for an @IBAction in Swift.

Say, I have a timer function, when countdown is finished, I need to call the Click-function @IBAction as below programmatically instead of asking user to click the button

How to do it in swift?


@IBAction func DoSomeTask(sender: UIButton) {

- code--

}
like image 529
MilkBottle Avatar asked Jun 29 '15 12:06

MilkBottle


3 Answers

You can either change the signature of the IBAction by making its parameter an Optional like this:

@IBAction func doSomeTask(sender: UIButton?) {
    // code
}

and then call it with nil as an argument:

doSomeTask(nil)

Or you can use the IBAction as a wrapper for the real function:

func doSomeTaskForButton() {
    // ...
}

@IBAction func doSomeTask(sender: UIButton) {
    doSomeTaskForButton()
}

meaning you can then call doSomeTaskForButton() from wherever you want.

like image 183
Eric Aya Avatar answered Nov 13 '22 14:11

Eric Aya


doSomeTask(UIButton()) in swift 5.0 and onward

like image 4
Hassan Kalhoro Avatar answered Nov 13 '22 14:11

Hassan Kalhoro


Do the same thing as @Moritz said but instead

@IBAction func doSomeTask(sender: UIButton? = nil) {
    // code
}

so that way, you do something like:

 `doSomeTask()`

which is saying the same thing as saying

 `doSomeTask(sender:nil)

or pass an UIButton object if you so wish so.

 doSomeTask(sender:SomeUIButton)
like image 1
Julio Rosario Avatar answered Nov 13 '22 14:11

Julio Rosario