Call IBAction from another method without a parameter

In my program, 2 functions (IBAction player.Move(UIButton) and autoMove() ) must be called in turn until all fields (UIButtons) are pressed. To do this, I created the play() function. However, I do not know how I can put an IBAction playerMove inside the play() function, because I do not need a parameter here.
I found some answers and tried self.playerMove(nil) and self.playerMove(self) , but that didn't work.

 import UIKit class ViewController: UIViewController { @IBOutlet var cardsArray: Array<UIButton> = [] var randomCard = 0 override func viewDidLoad() { super.viewDidLoad() self.play() // Do any additional setup after loading the view, typically from a nib. } func play () { self.autoMove() self.playerMove(self) // <----- here is my problem } @IBAction func playerMove(sender: UIButton) { switch (sender) { case self.cardsArray[0]: self.cardPressedAll(0) case self.cardsArray[1]: self.cardPressedAll(1) case self.cardsArray[2]: self.cardPressedAll(2) case self.cardsArray[3]: self.cardPressedAll(3) default: break } } func cardPressedAll (cardNumber: Int) { self.cardsArray[cardNumber].enabled = false self.cardsArray[cardNumber].setBackgroundImage(UIImage(named: "cross"), forState: UIControlState.Normal) self.cardsArray.removeAtIndex(cardNumber) } func autoMove (){ self.randomCard = Int(arc4random_uniform(UInt32(self.cardsArray.count))) self.cardsArray[self.randomCard].enabled = false self.cardsArray[self.randomCard].setBackgroundImage(UIImage(named: "nought"), forState: UIControlState.Normal) self.cardsArray.removeAtIndex(self.randomCard) } } 
+5
source share
2 answers

Or you need to call playerMove: without a button, in which case you need to declare the sender parameter as optional. How:

 @IBAction func playerMove(sender: UIButton?) { 

UIButton means you have to go through the button. nil not a button, but with UIButton? , i.e. Optional<UIButton> , nil is a valid value meaning no button.

Or you need to decide which button you want to pass to playerMove: to make it do what you want. Sit down and find out what you want and what needs to be done to make this happen.

+8
source

Try

 self.playerMove(UIButton()) 

Your func playerMove has options that expect sender to be of type UIButton , self or nil will be an unexpected object.

Edit: Can you specify additional parameters by posting ? . This will allow you to call self.playerMove(nil) if necessary.

 @IBAction func playerMove(sender: UIButton?) { if sender != nil { //handle when button is passed } else { //handle when nil is passed } } 
+3
source

Source: https://habr.com/ru/post/1208660/


All Articles