ThatMan
ThatMan

Reputation: 165

How can I add some func to button?

I have a function, setupGame(). When I press the play again button, the setupGame() function should be called. Where should I add this function?

let playAgain: UIButton = UIButton(frame: CGRectMake(-10, 400, 400, 150))

func setupGame() {
    score = 0
    physicsWorld.gravity = CGVectorMake(5, 5)
}

func buttonPressed(sender: UIButton) {

}

playAgain.setTitle("Play Again", forState: UIControlState.Normal)
playAgain.titleLabel!.font = UIFont(name: "Helvetica", size: 50) 
playAgain.addTarget(self, action: "buttonPressed:", forControlEvents: .TouchUpInside)
playAgain.tag = 1
self.view!.addSubview(playAgain)

Upvotes: 0

Views: 70

Answers (4)

Jojodmo
Jojodmo

Reputation: 23616

To call a function when a button is pressed, you should use UIButton.addTarget, which it looks like you already have. The problem is that you have the wrong action specified.

playAgain.addTarget(
    self,
    action: "buttonPressed:", // This should be "setupGame"
    forControlEvents: .TouchUpInside
)

The action parameter of the .addTarget function essentially points to the function that should be called. The little colon after the name is to indicate that the function should accept the sender of the action as an argument.

Assuming this is being added to a button, helloWorld: corresponds to func helloWorld(sender: UIButton), and helloWorld (notice the missing colon) corresponds to func helloWorld()

So, you should use

func setupGame() {
    score = 0
    physicsWorld.gravity = CGVectorMake(5, 5)
}

//button code

// Notice how the function above has no arguments,
// so there is no colon in the action parameter of
// this call
playAgain.addTarget(
    self, // the function to be called is in this class instance (self)
    action: "setupGame", // corresponds to the above setupGame function
    forControlEvents: .TouchUpInside
)

//other code

Upvotes: 0

Tim Vermeulen
Tim Vermeulen

Reputation: 12562

Simply replace "buttonPressed:" with "setupGame", and remove the buttonPressed function altogether.

Upvotes: 1

Rashwan L
Rashwan L

Reputation: 38843

If you want to use your storyboard you should add a button and then drag into your code (Outlet). Check this link of how to create an outlet connection.

Or you could create a button programmatically as you have done and call setupGame.

playAgain.addTarget(self, action: "setupGame", forControlEvents: .TouchUpInside)

Upvotes: 2

Dan Leonard
Dan Leonard

Reputation: 3405

You should make a IBAction instead of

func buttonPressed(sender: UIButton) {

}

but yes this is where the setupGame() function should be called

iBAction buttonPressed(sender:UIButton) {
   setupGame()
} 

and then just make sure you hook up your button to this function so it can detect the tapped interaction.

Upvotes: 0

Related Questions