I'm trying to have a feature where a button enables the digital crown. There are multiple tabs with this button, and I want to be able to scroll between the tabs and keep the mode/crown enabled.
So for above, my goal is the user could touch 'Enable Crown' and be able to swipe between tabs, keeping the digital crown mode enabled.
I believe that means maintaining focus on an element that has digitalCrownRotation() and focusable().
I got this working somewhat with the code below: if the 2nd tab is not active yet and I enable the crown and swipe to tab #2, the default focus modifier triggers #2 button to get focus and get the crown input.
But after that the buttons lose focus. I've tried various tricks and can't get it working. Complete code is at https://github.com/t9mike/DigitalCrownHelp3.
Any tips and ways to achieve my goal? Thank you.
import SwiftUI
class GlobalState : ObservableObject {
@Published var enableCrown = false
}
struct ChildView: View {
@State var crownValue = 0.0
@ObservedObject var globalState = ContentView.globalState
@Namespace private var namespace
@Environment(\.resetFocus) var resetFocus
let label: String
init(_ label: String) {
self.label = label
}
var body: some View {
ScrollView {
Text(label)
Button("\(globalState.enableCrown ? "Disable" : "Enable") Crown") {
globalState.enableCrown = !globalState.enableCrown
}
.focusable()
.prefersDefaultFocus(globalState.enableCrown, in: namespace)
.digitalCrownRotation($crownValue)
.onChange(of: crownValue, perform: { value in
print("crownValue is \(crownValue)")
})
}
.focusScope(namespace)
.onAppear {
print("\(label), enableCrown=\(globalState.enableCrown)")
resetFocus(in: namespace)
}
}
}
struct ContentView: View {
static let globalState = GlobalState()
var body: some View {
TabView {
ChildView("Tab #1")
ChildView("Tab #2")
}
}
}