2016-02-02 35 views
1

打印和func調用都是成功的,但是我的背景和標題只有在重新啓動我的應用程序並且只能運行1次時纔會更改。這裏是我的代碼:收到加速度計數據後爲什麼不改變我的背景和標題? SWIFT

var motionManager = CMMotionManager() 

override func viewDidAppear(animated: Bool) { 
    super.viewDidAppear(animated) 
    startMotionManager() 
} 

func startMotionManager() { 

    if motionManager.accelerometerAvailable { 
    motionManager.accelerometerUpdateInterval = 0.2 
    motionManager.startAccelerometerUpdatesToQueue(NSOperationQueue(), withHandler: { 
     [weak self] (data, error) in 

     print(data!.acceleration.z) 

     if(data!.acceleration.z > 0.8) { 
      self!.win() 
      print("Win") 
     } 

     if (data!.acceleration.z < -0.9){ 
      self!.pass() 
      print("Pass") 
     } 
     return 
     }) 
    } 

} 

func pass() { 
    print("passfunction") 
    self.testLabel.text = "PASS" 
    self.view.backgroundColor = UIColor.redColor() 
} 

func win() { 
    testLabel.text = "WIN" 
    view.backgroundColor = UIColor.greenColor() 
} 

}

我的主要目標就是調用FUNC贏時通acceleration.z> 0.8,其更改標題標籤爲「贏」與觀察背景爲綠色 如果acceleration.z < -0.9然後調用通行證功能,將我的背景變成紅色等...

感謝您的幫助!

+0

確保UIKit方法將從主線程調用! – CouchDeveloper

回答

1

我累了整天解決這個問題。在我發佈我的問題後,我在代碼中發現了問題。

func pass() { 
     NSOperationQueue.mainQueue().addOperationWithBlock { 

     self.testLabel.text = "PASS" 
     self.view.backgroundColor = UIColor.redColor() 
     } 
    } 
+0

沒錯 - 總是在主線程上調用UIKit方法但通常,使用'dispatch_async(dispatch_get_main_queue()){...}'更短。 – CouchDeveloper