2016-02-25 81 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