Skip to main content

How to read the Digital Crown on watchOS using digitalCrownRotation()

About 2 minSwiftSwiftUIArticle(s)bloghackingwithswift.comcrashcourseswiftswiftuixcodeappstore

How to read the Digital Crown on watchOS using digitalCrownRotation() 관련

SwiftUI by Example

Back to Home

How to read the Digital Crown on watchOS using digitalCrownRotation() | SwiftUI by Example

How to read the Digital Crown on watchOS using digitalCrownRotation()

Updated for Xcode 15

SwiftUI exposes the Digital Crown to our app with two modifiers, both of which must be used in order to use the crown as input for our app. The first is focusable(), which should be true when you want the view in question to be able to receive Digital Crown updates, and digitalCrownRotation(), which creates a binding between the Digital Crown and a property of your choosing.

Here’s a trivial example to get you started:

struct ContentView: View {
    @State var scrollAmount = 0.0

    var body: some View {
        Text("Scroll: \(scrollAmount)")
            .focusable(true)
            .digitalCrownRotation($scrollAmount)
    }
}

That will scroll from negative infinity to plus infinity, showing the current scroll value in a text view.

Tips

If you put focusable() after digitalCrownRotation() you’ll find it no longer works.

The digitalCrownRotation() modifier has a couple of other forms to give you more control over how it behaves. For example, the longest variety lets us:

  1. from and through set a range for the scroll.
  2. by sets a step amount, controlling how much to change each time the crown turns
  3. sensitivity determines how much the crown needs to be moved to trigger a change
  4. isContinuous determines whether the value wraps around when it reaches the minimum or maximum, or whether it just stops at those bounds.
  5. isHapticFeedbackEnabled determines whether haptic feedback is triggered on turns.

For example, this modifier steps through from 1 through 5 by 0.1 increments, with a low sensitivity, wrapping around from start to finish, with haptic feedback:

.digitalCrownRotation($scrollAmount, from: 1, through: 5, by: 0.1, sensitivity: .low, isContinuous: true, isHapticFeedbackEnabled: true)
Similar solutions…
How to make carousel lists on watchOS | SwiftUI by Example

How to make carousel lists on watchOS
How to create a date picker and read values from it | SwiftUI by Example

How to create a date picker and read values from it
How to make VoiceOver read characters individually | SwiftUI by Example

How to make VoiceOver read characters individually
How to create a segmented control and read values from it | SwiftUI by Example

How to create a segmented control and read values from it
How to read the red, green, and blue values from a Color | SwiftUI by Example

How to read the red, green, and blue values from a Color

이찬희 (MarkiiimarK)
Never Stop Learning.