How do I call a button function when the button is not being pressed
Make your sender argument optional and pass nil to ButtonPressed.
self.ButtonPressed( nil )
@IBAction func ButtonPressed( sender: AnyObject? ) {
println("Called Action")
}
One way would be to link your button up to its respective interface builder button and pass it into your function when you call it.
@IBOutlet weak var yourButton: UIButton!
self.buttonPressed(yourButton)
@IBAction func buttonPressed(sender: AnyObject) {
print("Called Action")
}
Alternatively, define your function like so, then you'll be able to call your method the same way as you did before:
@IBAction func buttonPressed(sender: AnyObject? = nil) {
print("Called Action")
}
// Call your method like this
self.buttonPressed()
// or this
self.buttonPressed(sender: nil)
Your ButtonPressed
function needs an argument sender
and yet you're not passing any when you call it. However, if you're doing this programatically, then you obviously don't have a sender
.
Two ways to get around this:
- Make the sender parameter an optional (
AnyObject?
instead ofAnyObject
) and invokeself.ButtonPress(nil)
. I just tried this and it works. - Put all the button press function in a separate function, e.g.,
performButtonPress()
. Call it from inside the IBAction outlet, and if you want to press the button programatically, directly callperformButtonPress()
.