我发现,当 macOS 中的输入字段接收到焦点时,以命令中规定的方式使用 @FocusedBinding
会导致持续崩溃。仅当 macOS 应用程序包含在 NavigationView
组件中时才会发生这种情况。
一旦发出 .focuedValue()
的组件接收到 focus,就会发生这种崩溃:
[General] 该窗口已被标记为需要在 Window pass 中另一个更新约束,但它在 Window pass 中的更新约束已经比窗口中的视图多。
如果我使用 HStack 切换 NavigationView,该应用程序将按照 SDK 描述的方式工作(每个 TextEditor 发出其 $post 可以被命令拾取,仅保持焦点编辑器的值处于活动状态)。
有人可以提供一些有关如何解决此问题的智慧吗?我在这里发现了 SwiftUI macOS 错误吗?
这是我的测试应用:
import SwiftUI
@main
struct TestApp: SwiftUI.App {
var body: some Scene {
WindowGroup {
ContentView()
}.commands {
AppCommands()
}
}
}
// MARK: Commands
struct AppCommands: Commands {
@CommandsBuilder var body: some Commands {
CommandMenu("Post") {
CommitPostCommand()
}
}
}
struct CommitPostCommand: View {
@FocusedBinding (\.post) var post
var body: some View {
Button(action: self.commitEditorText) {
Text("Save post")
}.keyboardShortcut(KeyEquivalent.return, modifiers: EventModifiers.command)
}
func commitEditorText() {
print("committing post \(post ?? "NIL")")
}
}
// MARK: FocusedValue Definition
struct FocusedPost: FocusedValueKey {
typealias Value = Binding<String>
}
extension FocusedValues {
var post: FocusedPost.Value? {
get { self[FocusedPost.self] }
set { self[FocusedPost.self] = newValue }
}
}
// MARK: UI Components
struct ContentView: View {
@State var post: String = "Hello World"
var body: some View {
NavigationView { // Switching this to HStack stops crash!
Text("Sidebar")
VStack {
InnerView()
InnerView()
ObserverView()
}
}
}
}
struct InnerView: View {
@State var post: String = ""
var body: some View {
TextEditor(text: $post)
.focusedValue(\.post, $post) // Commenting this out also stops crash
.padding()
}
}
struct ObserverView: View {
@FocusedValue (\.post) var post
var body: some View {
Text(post?.wrappedValue ?? "NIL")
}
}