4

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'

burnsi
  • 6,194
  • 13
  • 17
  • 27
Etihv
  • 43
  • 4

3 Answers3

6

This should help FocusState<Bool>().projectedValue

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

You can only create a FocusState<Bool>.Binding from a FocusState<Bool>, so you need access to a FocusState<Bool> in your preview. I usually do this sort of thing by turning my preview type into a View, like this:

struct ScoreView_Previews: PreviewProvider, View {
    @FocusState var focus = false

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

    static var previews: some View {
        Self()
    }
}
rob mayoff
  • 375,296
  • 67
  • 796
  • 848
  • Thank you Rob for your answer. However setting a default value for focus gets the message 'Argument passed to call that takes no arguments'. If I don't give this default value, the preview starts but crashes when I interact with it. I guess because the state in the view expects a value. I will leave it with this because I can use the preview in the MainContentView (which works perfectly). It just kept bugging me why I can't get it to work in ScoreView. – Etihv Feb 13 '23 at 08:15
0

If you’re using a Bool then it’ll require a value but if you use an Enum or other Hashable type for the FocusState, you can make it optional in your parent view and declare it the same way in your preview as:

@FocusState static var focus: SomeHashable?

Kyle Beard
  • 604
  • 5
  • 18