class ViewController: UIViewController {の下の行まで持っていきます。
ConnectionはOutletで、 Name をそれぞれ次のように設定して Connect をクリックしましょう。
xAccelLabel, yAccelLabel, zAccelLabel, xGyroLabel, yGyroLabel, zGyroLabel, xGravityLabel, yGravityLabel, zGravityLabel, pitchLabel, rollLabel, yawLabel
override func viewDidLoad() {の上の行まで持っていきます。 ConnectionはAction, Name はそれぞれ "tapStart", "tapStop" としてConnect をクリックしましょう。
@IBAction func tapStart(sender: AnyObject) { } @IBAction func tapStop(sender: AnyObject) { }という2行が追加されます。
ViewController.swiftに追加するコード(赤字部分) |
import UIKit import CoreMotion class ViewController: UIViewController { @IBOutlet weak var xAccelLabel: UILabel! @IBOutlet weak var yAccelLabel: UILabel! @IBOutlet weak var zAccelLabel: UILabel! @IBOutlet weak var xGyroLabel: UILabel! @IBOutlet weak var yGyroLabel: UILabel! @IBOutlet weak var zGyroLabel: UILabel! @IBOutlet weak var xGravityLabel: UILabel! @IBOutlet weak var yGravityLabel: UILabel! @IBOutlet weak var zGravityLabel: UILabel! @IBOutlet weak var pitchLabel: UILabel! @IBOutlet weak var rollLabel: UILabel! @IBOutlet weak var yawLabel: UILabel! let cmManager = CMMotionManager() @IBAction func tapStart(sender: AnyObject) { cmManager.deviceMotionUpdateInterval = 0.1 let handler:CMDeviceMotionHandler = { (motionData: CMDeviceMotion?, error: NSError?) -> Void in self.motionAnimation(motionData, error: error) } cmManager.startDeviceMotionUpdatesToQueue(NSOperationQueue.mainQueue(), withHandler: handler) } @IBAction func tapStop(sender: AnyObject) { if (cmManager.deviceMotionActive) { cmManager.stopDeviceMotionUpdates() } } func motionAnimation(motionData: CMDeviceMotion?, error: NSError?) { if let motion = motionData { xGyroLabel.text = String(format:"%.2f", motion.rotationRate.x) yGyroLabel.text = String(format:"%.2f", motion.rotationRate.y) zGyroLabel.text = String(format:"%.2f", motion.rotationRate.z) xAccelLabel.text = String(format:"%.2f", motion.userAcceleration.x) yAccelLabel.text = String(format:"%.2f", motion.userAcceleration.y) zAccelLabel.text = String(format:"%.2f", motion.userAcceleration.z) xGravityLabel.text = String(format:"%.2f", motion.gravity.x) yGravityLabel.text = String(format:"%.2f", motion.gravity.y) zGravityLabel.text = String(format:"%.2f", motion.gravity.z) pitchLabel.text = String(format:"%.2f", motion.attitude.pitch) rollLabel.text = String(format:"%.2f", motion.attitude.roll) yawLabel.text = String(format:"%.2f", motion.attitude.yaw) } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } |