crownSequencer equivalent in SwiftUI
Asked Answered
C

1

8

I've historically used the WKInterfaceController's property called "crownSequencer" to listen to rotations in the crown (see code below). I can grab the "rotationalValue" of the crown's rotation with the function 'crownDidRotate' as shown below.

import WatchKit
import Foundation

class InterfaceController: WKInterfaceController {

    override func awake(withContext context: Any?) {
        // Configure interface objects here.
    }

    override func willActivate() {
        // This method is called when watch view controller is about to be visible to user
    }

    override func didAppear() {
        super.didAppear()
        crownSequencer.delegate = self
        crownSequencer.focus()
    }

    override func didDeactivate() {
        // This method is called when watch view controller is no longer visible
    }

}

extension InterfaceController : WKCrownDelegate {
    func crownDidRotate(_ crownSequencer: WKCrownSequencer?, rotationalDelta: Double) {
        print(rotationalDelta)
    }
}

In SwiftUI, I can instead use the following code to listen to the crown within a View:



import SwiftUI
import SpriteKit

struct GameView: View {

    @State var scrollAmount: Float = 0.0

    // ...other code to initialise variables used

    var body: some View {
        SpriteView(scene: skScene!)
            .focusable(true)
            .digitalCrownRotation($scrollAmount, from: -70, through: 70, by: 0.1, sensitivity: .high, isContinuous: false, isHapticFeedbackEnabled: false)
            .onChange(of: scrollAmount) { newValue in
                //function )
            }
}

This code listens to rotations and binds the "scrollAmount" to a state variable.

However, I can't seem to grab an equivalent of the "rotationalDelta" from the original crownSequencer methodology. Is there a way to grab a "rotationalDelta" in SwiftUI (i.e, grab the change in rotation as opposed to the scrollAmount, which reflects the current level of rotation).

Catnip answered 12/10, 2022 at 12:31 Comment(0)
F
0

if I correct understood you just need to get a delta, if I am right it could be helpful for you:

.digitalCrownRotation(
                $scrollAmount,
                from: -100.0,
                through: 100.0,
                sensitivity: .low,
                isContinuous: true,
                isHapticFeedbackEnabled: true
            )
            .onChange(of: scrollAmount) { oldValue, newValue in
                let rotationalDelta = newValue - oldValue
                print(rotationalDelta)
            // any code
            }

You can't get delta from digitalCrownRotation(), but you can do it with onChange(), after update onChange can be with a two or zero parameters. Official documentation

Faveolate answered 28/8, 2024 at 9:39 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.