2017-04-02 47 views
-1

我想使while循環等待,直到用戶在Xcode上的Swift Playground中單擊UILabel。我怎樣才能做到這一點?如何等待用戶點擊UILabel?

這裏是我的循環

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

} 

例如,我要等待,直到用戶點擊opt1opt2,或opt3然後根據用戶點擊而做一些事情。

+0

永遠不要在主線程上運行一個無限循環等待發生的事情。將你的'UILabel'改成'UIButton'並使用'IBAction'。 –

+0

我將如何製作IBAction? –

回答

1

使用按鈕代替標籤併爲按鈕分配tag = 1,2和3。爲按鈕創建一個IBAction函數,並將所有按鈕連接到相同的函數。

使變量'n'爲全局。

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

希望這可以幫助你!