繁体   English   中英

如何向按钮添加一些功能?

[英]How can I add some func to button?

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

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)

如果要使用情节提要,则应添加一个按钮,然后将其拖到代码中(插座)。 检查链接以了解如何创建插座连接。

或者,您也可以通过编程方式创建一个按钮,然后调用setupGame。

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

只需将"buttonPressed:"替换为"setupGame" ,然后完全删除buttonPressed函数。

您应该进行IBAction而不是

func buttonPressed(sender: UIButton) {

}

但是是的,这是应该调用setupGame()函数的地方

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

然后只需确保将按钮连接到此功能,即可检测到被点击的交互。

要在按下按钮时调用函数,应该使用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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM