简体   繁体   中英

Label not updating swift

I am new to iOS. I am retrieving the data from the accelerometer using MotionKit. I can see on the terminal that the values from the accelerometer are being retrieved every 0.1 sec, unfortunately the label updates only one time. Why is the label not updating?

@IBOutlet weak var xLabel: UILabel!
@IBOutlet weak var yLabel: UILabel!
@IBOutlet weak var zLabel: UILabel!

var xAccel = 0.0
var yAccel = 0.0
var zAccel = 0.0


private let queue = NSOperationQueue()
let motionKit = MotionKit()




override func viewDidLoad() {
    super.viewDidLoad()

    motionKit.getAccelerometerValues(interval: 0.1){
        (x, y, z) in

        println("x: \(x)")
        println("y:  \(y)")
        println("z: \(z)")
        println();


        self.xAccel = x
        self.yAccel = y
        self.zAccel = z





        self.xLabel.text = "\(self.xAccel)"

        self.yLabel.text = "\(self.yAccel)"

        self.zLabel.text = "\(self.zAccel)"








    }

Since this MotionKit Framework executes as block you have to update the UILabels in the Main Queue, something like this will solve this problem but still really mess

import UIKit


class ViewController: UIViewController {
    @IBOutlet weak var xLabel: UILabel!
    @IBOutlet weak var yLabel: UILabel!
    @IBOutlet weak var zLabel: UILabel!

    var xAccel = 0.0
    var yAccel = 0.0
    var zAccel = 0.0


    private let queue = NSOperationQueue()
    let motionKit = MotionKit()

    override func viewDidLoad() {
        super.viewDidLoad()
        motionKit.getAccelerometerValues(interval: 0.1){
            (x, y, z) in

            println("x: \(x)")
            println("y:  \(y)")
            println("z: \(z)")
            println();


            self.xAccel = x
            self.yAccel = y
            self.zAccel = z

            dispatch_async(dispatch_get_main_queue(), {
                self.xLabel.text = "\(self.xAccel)"
                self.yLabel.text = "\(self.yAccel)"
                self.zLabel.text = "\(self.zAccel)"

            });

        }
    }

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


}

Hopethis helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM