[英]UILabel doesn't update the text called inside a core motion closure
每次設備震動時我都會嘗試更改UILabel的文本。 我需要一些解決方法來比UIEventSubtype震動更頻繁地捕捉震動。
調用motionMethod
,雖然我的UILabel文本在最終更新之前會保持相同的幾秒鍾。
所以這是我的代碼:
let delegate = (UIApplication.sharedApplication().delegate as AppDelegate)
var player:Player!
var motionManager: CMMotionManager?
let accThreshold = 1.0
var referenceTime = NSDate()
let timeThreshold = 0.2
override func viewDidLoad() {
super.viewDidLoad()
player = delegate.chancesPlayer
let queue = NSOperationQueue()
motionManager = delegate.motionManager
motionManager?.startDeviceMotionUpdatesToQueue(queue, withHandler: {
(motion: CMDeviceMotion!, error:NSError!) in
self.motionMethod(motion)
})
}
和motionMethod
:
func motionMethod(deviceMotion: CMDeviceMotion){
var acceleration = deviceMotion.userAcceleration
if fabs(acceleration.x) > accThreshold || fabs(acceleration.y) > accThreshold || fabs(acceleration.z) > accThreshold{
if -referenceTime.timeIntervalSinceNow > timeThreshold{
referenceTime = NSDate()
player.grow()
println("Player ist now at size: \(player.growth)") //this gets called frequently...
growthTF.text = "Player ist now at size: \(player.growth)" //...that doesn't
}
}
}
那么為什么文本更新有延遲?
您正在更新主(UI)線程以外的線程上的標簽,這是未定義的行為。 您應該使用GCD將主要線程分派回閉包內的UI更新,如下所示:
func motionMethod(deviceMotion: CMDeviceMotion){
var acceleration = deviceMotion.userAcceleration
if fabs(acceleration.x) > accThreshold || fabs(acceleration.y) > accThreshold || fabs(acceleration.z) > accThreshold{
if -referenceTime.timeIntervalSinceNow > timeThreshold{
referenceTime = NSDate()
player.grow()
dispatch_async(dispatch_get_main_queue()) {
growthTF.text = "Player ist now at size: \(player.growth)" //...that doesn't
}
}
}
}
或者,您可以指定更新應在主隊列上進行。
motionManager?.startDeviceMotionUpdatesToQueue(NSOperationQueue.mainQueue(), withHandler: {
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.