我编写了一个变量来跟踪迷你游戏中的分数,但是在执行某些代码后它并不能反映更新后的值。
我正在制作一个基本的智力竞赛迷你游戏,该游戏嵌入在iOS应用程序中。它在独立的视图控制器中运行,并且不与应用程序的任何其他部分交互。我的代码没有错误,但是当我尝试将UILabel设置为变量的值时,它没有任何变化...
@IBOutlet weak var imgItemImage: UIImageView!
@IBOutlet weak var lblItemName: UILabel!
@IBOutlet weak var lblScore: UILabel!
@IBAction func btnRedBin(_ sender: Any) {
trackScore(binChoice: "red")
}
@IBAction func btnYellowBin(_ sender: Any) {
trackScore(binChoice: "yellow")
}
@IBAction func btnGreenBin(_ sender: Any) {
trackScore(binChoice: "green")
}
var trashList:[String] = ["Can", "Brick", "Sandwich"]
var itemChoice:Int = 0
var score:Int = 0
var gameRound:Int = 0
func itemChange() {
if gameRound <= 3 {
itemChoice = Int.random(in: 0...((trashList.count)-1))
lblItemName.text = trashList[itemChoice]
imgItemImage.image = UIImage(named: (trashList[itemChoice]))
} else {
lblItemName.text = "You scored \(score) points!"
}
gameRound += 1
lblScore.text = "\(score)"
}
func trackScore(binChoice:String){
switch trashList{
case ["Can"]:
if binChoice == "red"{
score = score - 1
} else if binChoice == "yellow" {
score = score + 10
} else {
score = score - 5
}
case ["Brick"]:
if binChoice == "red"{
score = score + 10
} else if binChoice == "yellow" {
score = score - 1
} else {
score = score - 5
}
case ["Sandwich"]:
if binChoice == "red"{
score = score + 10
} else if binChoice == "yellow" {
score = score - 1
} else {
score = score - 5
}
default:
break
}
trashList.remove(at: itemChoice)
itemChange()
}
我希望当按下按钮(动作)之一时,变量“分数”会发生变化。但是,当我这样做并尝试通过将UILabel“ lblScore”设置为其值进行检查时,我总是得到0。
答案 0 :(得分:1)
这就是trackScore函数的外观
func trackScore(binChoice:String){
switch binChoice:String{
case "Can":
if binChoice == "red"{
score = score - 1
} else if binChoice == "yellow" {
score = score + 10
} else {
score = score - 5
}
case "Brick":
if binChoice == "red"{
score = score + 10
} else if binChoice == "yellow" {
score = score - 1
} else {
score = score - 5
}
case "Sandwich":
if binChoice == "red"{
score = score + 10
} else if binChoice == "yellow" {
score = score - 1
} else {
score = score - 5
}
default:
break
}
trashList.remove(at: itemChoice)
itemChange()
}
答案 1 :(得分:0)
在trackScore()
中,您switch
正在trashList
上,但是它通常包含多个项目,因此与您的情况不符。
您要:
func trackScore(binChoice:String){
switch trashList[itemChoice] {
case "Can":
if binChoice == "red"{
score = score - 1
} else if binChoice == "yellow" {
score = score + 10
} else {
score = score - 5
}
case "Brick":
if binChoice == "red"{
score = score + 10
} else if binChoice == "yellow" {
score = score - 1
} else {
score = score - 5
}
case "Sandwich":
if binChoice == "red"{
score = score + 10
} else if binChoice == "yellow" {
score = score - 1
} else {
score = score - 5
}
default:
break
}
trashList.remove(at: itemChoice)
itemChange()
}