首页 > 解决方案 > 如何使用for循环设置按钮图像取决于数组的值?

问题描述

我有这样的数组,它的计数不固定

var option = ["0","1","0","1","1","0","0"]

带按钮阵列

var buttons = [firstBtn,secondBtn,thirdBtn]

我需要根据选项数组值设置按钮图像

option[0] = "0", firstBtn.setImage(zeroImage, for: .normal)
option[0] = "1", firstBtn.setImage(firstImage, for: .normal)

我在下面尝试过

for button in buttons { 
        for value in option {
              if value == "0" {
                    button?.setImage(zeroImage, for: .normal)
              }else {
                    button?.setImage(firstImage, for: .normal)
              }
            }
          }

但这可能会导致内部 for-loop 将不断获取 next 直到它完成,然后返回外部 for-loop

我需要任何按钮都有自己的图像

此外,我的选项计数不固定

这应该取决于我有多少按钮

我应该如何解决我的问题?

标签: swift

解决方案


创建如下按钮集合

@IBOutlet var buttonsCollection: [UIButton]!    // set tags for button on storyboard or xib or assign programmatically if creating button programatically

创建名为长度等于buttonsCollection的图像数组

var option = ["0","1","0","1","1","0","0"]

然后简单地使用每个循环

for button in buttonsCollection {
                button?.setImage(option[button.tag], for: .normal)
      }

或者,如果我们同意您的实施

var option = ["0","1","0","1","1","0","0"] // make sure option array should be greatert than or equal to buttons array
 // set tags for button on storyboard or xib or assign programmatically if creating button programatically

var buttons = [firstBtn,secondBtn,thirdBtn]       
for button in buttons {
        button?.setImage(option[button.tag], for: .normal) 
          }

注意:对于这两种情况,请确保在两个数组中为按钮及其标题设置相同的索引


推荐阅读