有谁知道为什么我不能让UILabel在queryPedometerDataFromDate内部进行更改,即使它会在其外部进行更新?运行查询后,我试图将stepCount发布到标签。起初我以为这是一个NSNumber到String的转换问题,但是两个打印语句都向控制台输出了相同的值。任何指导将不胜感激。我对这些东西很陌生。

var pedometer = CMPedometer()

    @IBOutlet weak var stepsLabel: UILabel!
    @IBAction func queryStepCount(sender: AnyObject) {

        if CMPedometer.isStepCountingAvailable() {

            let now = NSDate()
            let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
            let midnightOfToday = calendar!.startOfDayForDate(now)
            var stepCount = NSNumber(integer: 0)

            self.pedometer.queryPedometerDataFromDate(midnightOfToday, toDate: now, withHandler: { (CMPedometerData, error) -> Void in

                stepCount = CMPedometerData!.numberOfSteps
                let convertedStepCount = stepCount.stringValue
                print("Converted Step Count:" + convertedStepCount)
                print (stepCount)

                // Why doesn't this change my label text?
                self.stepsLabel.text = "CHANGED"

            })

            // But this does...
            self.stepsLabel.text = "CHANGED"

        }

最佳答案

如果查询不在主线程上执行,则行self.stepsLabel.text = "CHANGED"不会更新UI。尝试这个...

dispatch_async(dispatch_get_main_queue(),{
    self.stepsLabel.text = "CHANGED"
})

09-29 21:29