2016-02-25 143 views
0

我有一个功能,setupGame()。当我再次按下播放按钮时,应该调用setupGame()函数。我应该在哪里添加这个功能?如何添加一些func到按钮?

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) 

回答

2

如果你想使用你的故事板,你应该添加一个按钮,然后拖入你的代码(Outlet)。检查this如何创建插座连接的链接。

或者您可以按照编程方式创建按钮,然后调用setupGame。

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

你应该做的,而不是

func buttonPressed(sender: UIButton) { 

} 

一个IBAction为,但肯定这就是setupGame()功能应该被称为

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

,然后只是确保你的按钮挂接到这个功能,所以它可以检测到窃听的互动。

1

只需使用"setupGame"替换"buttonPressed:",并完全消除buttonPressed功能。

0

要在按下按钮时调用某个函数,您应该使用UIButton.addTarget,它看起来像您已有的。问题是你指定了错误的动作。

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

.addTarget功能的action参数主要指向应该调用的函数。名称后的小冒号表示函数应该接受动作的发送者作为参数。

假设这是被添加到一个按钮,helloWorld:对应func helloWorld(sender: UIButton),并helloWorld(注意缺少冒号)对应于func helloWorld()

所以,你应该用

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