In my current swift program, one function display real time acceleration data on screen with line. So I used class drawRect
. As a result, the acceleration figure can be drawn, but not real time everytime I refresh it (turn down the App and reopen). I know that I should use some method such as setNeedsDisplay()
to redraw it. But it was no use. Maybe I wrote it in a wrong way. Here is my code:
import UIKit
import CoreMotion
class draw: UIView, UIAccelerometerDelegate {
var motionManager = CMMotionManager()
override func drawRect(rect: CGRect) {
motionManager.deviceMotionUpdateInterval = 0.1
var acc_x: Double = 0.0
var temp_x: Double = 0.0
var i: CGFloat = 0
var accLine_x = UIGraphicsGetCurrentContext()
if(motionManager.deviceMotionAvailable) {
var queue = NSOperationQueue.mainQueue()
motionManager.startDeviceMotionUpdatesToQueue(queue, withHandler: {
(deviceMotion: CMDeviceMotion!, error: NSError!) in
temp_x = acc_x
acc_x = deviceMotion.userAcceleration.x
CGContextSetLineWidth(accLine_x, 2)
CGContextSetStrokeColorWithColor(accLine_x, UIColor.redColor().CGColor)
CGContextMoveToPoint(accLine_x, i + 10, self.screenHeight * 436 + CGFloat(temp_x * 100))
CGContextAddLineToPoint(accLine_x, i + 13, self.screenHeight * 436 + CGFloat(acc_x * 100))
CGContextStrokePath(accLine_x)
i = (i + 3) % 320
})
}
}
}