如何通过按其他按钮更改一个按钮的图像?

时间:2015-10-26 17:58:17

标签: swift loops uibutton uiimage switch-statement

在viewcontroller上我有101个按钮。如果按下前100个按钮之一,我想更改按钮编号101的图像(我在此项目中有100个图像;图像1,图像2,图像3等)。

所以我这样做了,给每个按钮一个0-100的标签,然后根据sender.tag发表一个switch语句

@IBOutlet weak var button101 : UIButton!

var i = 1

  // I hooked up all the other 100 buttons to a single IBAction
  @IBAction func buttonTapped(sender: UIButton) {

 switch sender.tag {

case 0:  i = 1

  let image = UIImage (named: "image\(i)")
  button101.setImage(image, forState:.Normal)

case 1:   i = 2

  let image = UIImage (named: "image\(i)")
  button101.setImage(image, forState:.Normal)

case 2:   i = 3

 let image = UIImage (named: "image\(i)")
  button101.setImage(image, forState:.Normal)

case ..: // etc. until case 99 (because button 100 has tag 99)

default: break

这个超级丑陋的代码有效:它将按钮号101的图像更改为指定的图像(i)。但我想要一个更优雅,更好的解决方案。

我有两个问题:

  1. 如何初始化'图像'更好的方式是恒定/变量(在IBAction之外)?
  2. 使用什么类型的(循环)语句代替这个大的switch语句? 所以:我想确定按下哪个按钮,然后更新var i的值,遍历图像,找到并用图像(i)更新button101的图像。
  3. 我希望我的问题很明确。如果不是,请告诉我。 非常感谢帮助!

1 个答案:

答案 0 :(得分:1)

您的switch语句与:

相同
if sender.tag < 100 {
    let image = UIImage (named: "image\(sender.tag + 1)")
    button101.setImage(image, forState:.Normal)
}

如果您愿意,可以将UIImage置于ViewController的{​​{1}}顶部,但我认为没有理由这样做。

相关问题