可以在视图主体之外访问 FocusState 的值

It is possible to accessing FocusState's value outside of the body of a View

我想将我的@FocusState 驱逐到我的 viewModel 中:

struct ContentView: View {
    @ObservedObject private var viewModel = ViewModel()
    
    var body: some View {
        Form {
            TextField("Text", text: $viewModel.textField)
                .focused(viewModel.$hasFocus)
            Button("Set Focus") {
                viewModel.hasFocus = true
            }
        }
    }
}

class ViewModel: ObservableObject {
    @Published var textField: String = ""
    @FocusState var hasFocus: Bool
}

但是当我启动我的应用程序时,我收到了这个 SwiftUI 警告:

runtime: SwiftUI: Accessing FocusState's value outside of the body of a View. This will result in a constant Binding of the initial value and will not update.

在这种情况下,我的绑定永远不会改变。

我的问题是:可以在 viewModel 中使用 FocusState 吗?

它是视图中的包装器(与 State 相同)。但是可以将其映射到已发布的 属性,就像下面的方法一样。

测试 Xcode 13.2 / iOS 15.2

struct ContentView: View {
    @ObservedObject private var viewModel = ViewModel()
    @FocusState var hasFocus: Bool

    var body: some View {
        Form {
            TextField("Text", text: $viewModel.textField)
                .focused($hasFocus)
                .onChange(of: viewModel.hasFocus) {
                    hasFocus = [=10=]
                }
                .onChange(of: hasFocus) {
                    viewModel.hasFocus = [=10=]
                }
            Button("Set Focus") {
                viewModel.hasFocus = true
            }
        }
    }
}

class ViewModel: ObservableObject {
    @Published var textField: String = ""
    @Published var hasFocus: Bool = false
}