簡體   English   中英

Swift-在func中使用IBOutlet和IBAction嗎?

[英]Swift - Using IBOutlet & IBAction in func?

我在櫃台上工作。 60秒過后,我想停止他的工作。 為此,我使用以下代碼:

class FirstViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    //calling the wait function
    self.callForWait()    
}

func game(){        
    var score : Int = 0

    @IBOutlet weak var afficheurScore: UILabel!

    @IBAction func boutonPlus(sender: UIButton) {

        score = score + 1

        afficheurScore.text = "\(score)"   
    }
}

func callForWait(){
    //setting the delay time 60secs.
    let delay = 60 * Double(NSEC_PER_SEC)
    let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
    dispatch_after(time, dispatch_get_main_queue()) {
        //call the method which have the steps after delay.
        self.stepsAfterDelay()
    }
}

func stepsAfterDelay(){
    //your code after delay takes place here...
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
}

boutonPlus是一個按鈕,當我單擊afficheurScore時,一個簡單的標簽說(number + 1)。

在我的游戲功能中,我遇到了以下錯誤:

“只能將實例屬性聲明為IBOutlet / IBAction”

將此代碼移出game()函數

    @IBOutlet weak var afficheurScore: UILabel!

    @IBAction func boutonPlus(sender: UIButton) {
        score = score + 1
        afficheurScore.text = "\(score)"

    }

因此,您可以在類級別使用它,現在它們已 game()函數中定義

完整的代碼應為:

class FirstViewController: UIViewController {

  var score : Int = 0

  @IBOutlet weak var afficheurScore: UILabel!

  @IBAction func boutonPlus(sender: UIButton) {
        score = score + 1
        afficheurScore.text = "\(score)"
  }

  override func viewDidLoad() {
    super.viewDidLoad()
    //calling the wait function
    self.callForWait()
  }

  func game(){
  }

  func callForWait(){
    //setting the delay time 60secs.
    let delay = 60 * Double(NSEC_PER_SEC)
    let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
    dispatch_after(time, dispatch_get_main_queue()) {
        //call the method which have the steps after delay.
        self.stepsAfterDelay()
    }
  }


  func stepsAfterDelay(){
    //your code after delay takes place here...
  }

  override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM