Why @FocusState Crashing SwiftUI Preview

Viewed 1484

Okay, I wanted to know why my preview wasn't working after updating Xcode. So I have an enum that looks like this.

enum Field {
    case email
    case securedPassword
    case unsecuredPassword
}

Now when I add @FocusState to my TestView my preview just crashes and doesn't update. Here is how my code looks like.

struct TestView1: View {
    @FocusState var focusedField: Field?
    
    var body: some View {
        Color.blue
    }
}

Now when I comment out the @FocusState I am able to change the color to something like red and the preview updates. When the @FocusState is not commented out, when I change the color to something new it doesn't update the preview and gives me a weird crash.

Now is this a bug and if so is there a work around?

1 Answers

Please see my related answer I posted a couple of months ago on the Apple Developer Forums located at: https://developers.apple.com/forums/thread/681571?answerId=690251022#690251022 . Does this work for you?

struct TestView1: View {
    enum Field: Hashable {
        case email
        case securedPassword
        case unsecuredPassword
    }

    @FocusState var focusedField: Field?
    
    var body: some View {
        Form {
            Color.blue
        }
    }
}

struct TestView1_Previews: PreviewProvider {
    static var previews: some View {
        // Here we've wrapped `TestView1` in a `ZStack { ... }` View
        // so that it won't be the top-level View in our Preview, to avoid
        // the known bug that causes the `@FocusState` property of a
        // top-level View rendered inside of a Preview, to not work properly.
        ZStack {
            TestView1()
        }
    }
}
Related