【发布时间】:2015-10-29 17:37:37
【问题描述】:
我有一个项目,其中显示了一些 UIbuttons 和不同的 UIimages。通过用户交互,UIButtons 中可能有任何UIimages。项目中有大约 1000 张图像。我已经初始化了一个名为“i”的变量。还有一个名为 buttonTapped 的 IBAction 所有按钮。现在我想更新变量“i”并为每个可能的“UIImage”使用“i”的值。我可以使用 IF 语句来做到这一点,如下所示:
@IBAction func buttonTapped(sender: UIButton) {
if sender.currentImage == UIImage(named: "image1") {
i = 1
print(i)
// use the value of i
} else if sender.currentImage == UIImage(named: "image2") {
i = 2
print(i)
// use the value of i
} else if sender.currentImage == UIImage(named: "image3") {
i = 3
print(i)
// use the value of i
} else if // and so on
但我想要一个更好的解决方案,然后是一个包含大约 1000 个 else if(s) 的 IF 语句。我已经尝试过,但我无法简洁地重写代码。我可以用什么来代替 IF 语句?某种循环?
【问题讨论】:
标签: swift loops if-statement uibutton uiimage