为什么 @FocusState 会导致 SwiftUI 预览版崩溃

Lui*_*rez 11 swiftui

好吧,我想知道为什么我的预览在更新 Xcode 后不起作用。所以我有一个看起来像这样的枚举。

enum Field {
    case email
    case securedPassword
    case unsecuredPassword
}
Run Code Online (Sandbox Code Playgroud)

现在,当我将 @FocusState 添加到 TestView 时,我的预览会崩溃并且不会更新。这是我的代码的样子。

struct TestView1: View {
    @FocusState var focusedField: Field?
    
    var body: some View {
        Color.blue
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,当我注释掉 @FocusState 时,我可以将颜色更改为红色,并且预览会更新。当 @FocusState 未注释掉时,当我将颜色更改为新颜色时,它不会更新预览并给我带来奇怪的崩溃。

现在这是一个错误吗?如果是,有解决办法吗?

Jer*_*son 46

请参阅我几个月前在 Apple 开发者论坛上发布的相关答案,网址为: https: //developers.apple.com/forums/thread/681571 ?answerId=690251022#690251022 。这对你有用吗?

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()
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 是的,这是通过将 TestView1 嵌套到预览内的 ZStack 中来实现的。谢谢。 (2认同)