gpt4 book ai didi

arrays - 如何修复我的随机按钮启用代码每次都显示相同的顺序?

转载 作者:行者123 更新时间:2023-11-30 10:44:51 25 4
gpt4 key购买 nike

我有 15 UIButtons在我的界面中,首先所有按钮都被模糊/禁用。我有代码随机生成从 1 到 15 的数字数组,然后将这些数字用作我的每个 UIButton's 上的标签。 。然后我循环按钮并查看标签数组是否包含我当前正在循环的按钮标签。

func assignLabels() {

//Loop through the array of buttons.
for button in buttons {

//Check to see if the array of tags contains the current button tag.
if tags.contains(button.tag){

print(button.tag)
button.layer.cornerRadius = 8
button.alpha = 1.0
button.isUserInteractionEnabled = true

switch onStage{
case 1:
currentPhoneme = stage1[currentPhonemeNumber]
button.setTitle(stage1[currentTag], for: .normal)
// button.setTitle(button.tag.description, for: .normal)
case 2:
currentPhoneme = stage2[currentPhonemeNumber]
button.setTitle(stage2[currentTag], for: .normal)
default:
currentPhoneme = stage1[currentPhonemeNumber]
button.setTitle(stage1[currentTag], for: .normal)
}
}else{
button.alpha = 0.3
button.setTitle("-", for: .normal)
}
currentTag += 1
if currentTag == stageCount{
break
}
}
}

应该发生的是,当我们循环按钮时,它会检查按钮标签是否在标签数组中,然后启用该按钮并为其分配标签。尽管这有效,但每次调用代码时我都会得到相同的按钮顺序,即使按钮标签完全随机,下面是我在界面中得到的内容。 Check here

应该发生的是,每次调用该函数时,启用的按钮都应该在屏幕上以随机顺序排列,就像每次都有不同的模式一样。对这种行为的任何帮助都会很棒,因为我不知道为什么顺序总是相同的!

最佳答案

您的顺序始终相同,因为您是根据顺序相同的 currentTag 变量分配标签。此外,无论顺序如何,contains 都会返回相同的结果。

一个简单的修复方法是重新排序按钮的标签并使用按钮的标签而不是 currentTag:

func assignLabels() {

// New random button tag order
let newtags = Array(1...buttons.count).shuffled()

// Loop through the array of buttons.
for (button, newtag) in zip(buttons, newtags) {

// Assign new tag to button
button.tag = newtag

//Check to see if the array of tags contains the current button tag.
if tags.contains(button.tag){

let currentTag = button.tag

...

}

请务必删除此代码,因为不需要:

currentTag += 1
if currentTag == stageCount{
break
}

关于arrays - 如何修复我的随机按钮启用代码每次都显示相同的顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55951730/

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