UILabel不会更新核心动作闭包中调用的文本

时间:2014-07-22 14:14:47

标签: ios swift uilabel closures accelerometer

每次设备震动时,我都会尝试更改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
        }
    }
}

那么为什么文本更新有延迟?

1 个答案:

答案 0 :(得分:4)

您正在更新主(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: {