Search code examples
swiftuibindingpreview

How to set a value for @FocusState in SwiftUI Preview


I'm passing a FocusState-property of a textfield to a childview. This works as expected. In this childview I want to get the preview working, however I can't seem to set a contant value for the Focusstate. Anyone ideas?

struct MainContentView: View {
@FocusState private var focusedField: Bool

    var body: some View { 
        ScoreView(focussed: $focusedField)
    }
}

struct ScoreView: View {
@FocusState.Binding var focussed: Bool

    var body: some View {
        someSubView(focussed: $focussed)
    }
}

struct ScoreView_Previews: PreviewProvider {

    static var previews: some View {
        ScoreView(focussed: ????????). <- here
    }
}

I expected to be able to set a constant for the state-property just like with @State boolean properties, but I get the message:

Type 'FocusState.Binding' has no member 'constant'


Solution

  • This should help FocusState<Bool>().projectedValue

    struct ScoreView_Previews: PreviewProvider {
        static var previews: some View {
            ScoreView(focussed: FocusState<Bool>().projectedValue)
        }
    }