Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save xfer/1db9ddf92c1b06ba7cafb075f5e61163 to your computer and use it in GitHub Desktop.
Save xfer/1db9ddf92c1b06ba7cafb075f5e61163 to your computer and use it in GitHub Desktop.
Accelerometer
import UIKit
import CoreMotion
class ViewController: UIViewController {
@IBOutlet weak var wallpaper: UIImageView!
@IBOutlet weak var welcomeLabel: UILabel!
var motionManager: CMMotionManager!
override func viewDidLoad() {
super.viewDidLoad()
motionManager = CMMotionManager()
motionManager.startAccelerometerUpdates(to: .main, withHandler: updateImageView)
}
private func apply(accelerometerData acceleration: CMAcceleration, into view: UIView, multiplier: CGFloat) {
let yOffset = CGFloat(acceleration.y) * multiplier
let xOffset = CGFloat(acceleration.x) * multiplier
view.transform = CGAffineTransform(translationX: xOffset, y: yOffset)
}
func updateImageView(data: CMAccelerometerData?, error: Error?) {
if let accelerometerData = motionManager.accelerometerData {
apply(accelerometerData: accelerometerData.acceleration, into: wallpaper, multiplier: 100.0)
apply(accelerometerData: accelerometerData.acceleration, into: welcomeLabel, multiplier: 50.0)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment