gpt4 book ai didi

swift - 使用按钮在 swift 中切换语句

转载 作者:行者123 更新时间:2023-11-30 10:23:09 26 4
gpt4 key购买 nike

我无法弄清楚如何在 swift 中使用我的 switch 语句,以便当我单击任一按钮时它将执行 println()。每次我单击任一按钮时,它都会执行默认值。

class ViewController: UIViewController{

var addOne : UIButton = UIButton(frame: CGRectMake(0, 0, 40, 40))
var addFive : UIButton = UIButton(frame: CGRectMake(0, 0, 40, 40))

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.

addOne.setTitle("+1", forState: UIControlState.Normal)
addOne.backgroundColor = UIColor.blackColor()
addOne.center = (CGPointMake(40, 250))
addOne.addTarget(self, action: "player", forControlEvents: UIControlEvents.TouchUpInside)
view.addSubview(addOne)

addFive.setTitle("+5", forState: UIControlState.Normal)
addFive.backgroundColor = UIColor.blackColor()
addFive.center = (CGPointMake(200, 250))
addFive.addTarget(self, action: "player", forControlEvents: UIControlEvents.TouchUpInside)
view.addSubview(addFive)
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

func player(){

switch (true){

case addOne:
println("goodbye")
case addFive:
println("hello world")

default:
println("hello")
}

}

}

最佳答案

更改此:

addOne.addTarget(self, action: "player", forControlEvents: UIControlEvents.TouchUpInside)

对此:

addOne.addTarget(self, action: "player:", forControlEvents: UIControlEvents.TouchUpInside)

还有这个:

addFive.addTarget(self, action: "player", forControlEvents: UIControlEvents.TouchUpInside)

对此:

addFive.addTarget(self, action: "player:", forControlEvents: UIControlEvents.TouchUpInside)

注意“player:”中添加的冒号

下一步,更改此:

func player(){

switch (true){

case addOne:
println("goodbye")
case addFive:
println("hello world")

default:
println("hello")
}

}

对此:

func player(sender: UIButton){

switch (sender){

case addOne:
println("goodbye")
case addFive:
println("hello world")

default:
println("hello")
}

}

关于swift - 使用按钮在 swift 中切换语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24843718/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com