如何修正我的随机按钮启用码每次显示相同的顺序?

时间:2019-05-02 11:44:07

标签: arrays swift loops uibutton

我的界面中有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

应该发生的是,每次调用该功能时,启用的按钮应在屏幕上以随机顺序排列,就像每次使用不同的样式一样。对于这种行为的任何帮助都将是巨大的,因为我不知道为什么顺序总是相同!

1 个答案:

答案 0 :(得分:0)

您的顺序总是相同的,因为您是根据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
}