-1

I want to make a while loop wait until a user clicks on a UILabel in a Swift Playground on Xcode. How can I do this?

Here's my loop

func gameLoop() {

    while(score >= 0) {

        let n = arc4random_uniform(3)

        if(n == 0) {
            opt1.text = rightStatements.randomElement()
            opt2.text = wrongStatements.randomElement()
            opt3.text = wrongStatements.randomElement()
        } else if(n == 1) {
            opt1.text = wrongStatements.randomElement()
            opt2.text = rightStatements.randomElement()
            opt3.text = wrongStatements.randomElement()
        } else if(n == 2) {
            opt1.text = wrongStatements.randomElement()
            opt2.text = wrongStatements.randomElement()
            opt3.text = rightStatements.randomElement()
        }
    }

}

For example, I want to wait until the user either clicks opt1, opt2, or opt3 Then do something based on what the user clicks.

Jordan Baron
  • 165
  • 1
  • 15

1 Answers1

1

Use Buttons instead of Labels and assign tag = 1, 2, and 3 for buttons. Create an IBAction function for the buttons and connect all the buttons to the same function.

Make variable 'n' as global.

var n = Int()

func nextAttempt() {

    if(score >= 0) {

        n = arc4random_uniform(3)

        if(n == 0) {
            opt1.text = rightStatements.randomElement()
            opt2.text = wrongStatements.randomElement()
            opt3.text = wrongStatements.randomElement()
        } else if(n == 1) {
            opt1.text = wrongStatements.randomElement()
            opt2.text = rightStatements.randomElement()
            opt3.text = wrongStatements.randomElement()
        } else if(n == 2) {
            opt1.text = wrongStatements.randomElement()
            opt2.text = wrongStatements.randomElement()
            opt3.text = rightStatements.randomElement()
        }
    }
   else
    {
      //Score < 0
      //Game Over
    }

 }


@IBAction func onButtonClick(_ sender: Any)
{
switch(sender.tag)
   {
    case 1:
      if (n==0)
       {
         //Right button tapped
         //Update score if you want
       }
      else
       {
         self.nextAttempt()
        }
  case 2:
     if (n==1)
      {
       //Right button tapped
       //Update score if you want
      }
     else
     {
       self.nextAttempt()
     }
  case 3:
    if (n==2)
    {
       //Right button tapped
       //Update score if you want
    }
    else
    {
      self.nextAttempt()
    }
  }
}

Hope this helps you!!

MBN
  • 304
  • 1
  • 12