iosiphoneswiftmotiontilt

Generating a UIColor with arguments tilt value data in swift


I'm trying to make an app which will change the colour of the background based on the tilt angle of the device. I'm having no problem finding the tilt values of the device, I just can't seem to use the tilt values as parameters in a UIColor.

I have the following code:

let manager = CMMotionManager()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    manager.gyroUpdateInterval = 0.1
    manager.startGyroUpdates()

    if manager.deviceMotionAvailable {
        manager.deviceMotionUpdateInterval = 0.01
        manager.startDeviceMotionUpdatesToQueue(NSOperationQueue.mainQueue()) {
            [weak self] (data: CMDeviceMotion!, error: NSError!) in

            let xColor = data.gravity.x


            self!.view.backgroundColor = UIColor(red: 155/255, green: xColor, blue: 219/255, alpha: 1)
        }
    }

}

You would think that it would generate a color that varied depending on the x-tilt of the device, but it doesn't. The type is not supported.

Does anybody know how I could use the "xColor" variable to change the green level of the background color?


Solution

  • The problem is that data.gravity.x returns a Double and UIColor is expecting a CGFloat value between 0.0 and 1.0. You will need to convert your Double to CGFloat and also use the abs() method to make extract positive numbers from negative ones.

    import UIKit
    import CoreMotion
    class ViewController: UIViewController {
        let motionManager = CMMotionManager()
        override func viewDidLoad() {
            super.viewDidLoad()
            motionManager.gyroUpdateInterval = 0.1
            motionManager.startGyroUpdates()
            if motionManager.deviceMotionAvailable {
                motionManager.deviceMotionUpdateInterval = 0.01
                motionManager.startDeviceMotionUpdatesToQueue(NSOperationQueue.mainQueue(), withHandler: { (data: CMDeviceMotion!, error: NSError!) -> Void in
                    let x = data.gravity.x
                    let y = data.gravity.y
                    let z = data.gravity.z
                    self.view.backgroundColor = UIColor(
                        red: CGFloat(abs(x)),
                        green: CGFloat(abs(y)),
                        blue: CGFloat(abs(z)),
                        alpha: 1.0)
                })
            }
        }
        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }
    }