Contents

deviceMotionBody

A physical body or view that defines the coordinate system for device-motion data.

Declaration

var deviceMotionBody: (any CMBodyIdentifiable)? { get set }

Discussion

Set this property to associate device-motion calculations with a specific body or view, such as a UIKit UIView that conforms to CMBodyIdentifiable.

When this property is nil, Core Motion calculates motion updates using the device’s hardware coordinate frame. When you set this property to an identifiable body, Core Motion transforms motion data, including 3D orientation, rotation rate, gravity, and user acceleration to match the current orientation of that view. The system updates this transformation automatically whenever the view rotates or changes position.

On iPhone Duo, setting this property also identifies which display your app occupies. For example, when iPhone Duo is seated with the camera-side down on a surface, setting deviceMotionBody to your view allows your app to receive motion data relative to that active display and detect which face is up.

Because coordinate transformations apply directly to each specified view rather than across the entire app, you can create separate motion manager instances for different views. For example, an app can display two distinct bubble levels side by side across separate views to check surface tilt, with one level tracking horizontal alignment and the other tracking vertical alignment. Each motion manager tracks its own view orientation independently.

let motionManager = CMMotionManager()

override func viewDidLoad() {
    super.viewDidLoad()
    
    // Align device motion with this view's orientation.
    motionManager.deviceMotionBody = view
    
    motionManager.startDeviceMotionUpdates(using: .xTrueNorthZVertical, to: .main) { motion, error in
        guard let motion else { return }
        // Motion data automatically aligns with the view's current orientation.
    }
}

Topics

Motion configuration

See Also

Managing device motion updates