gpt4 book ai didi

swift - 如何使用for循环根据数组的值设置按钮图像?

转载 作者:行者123 更新时间:2023-11-30 10:38:47 27 4
gpt4 key购买 nike

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

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循环会不断地获取next直到完成,然后回到外部for循环

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

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

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

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

最佳答案

创建如下按钮集合

@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)
}

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

关于swift - 如何使用for循环根据数组的值设置按钮图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57303432/

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