macOS SwiftUI使用focusedSceneValue取值始终为nil问题求助
核心问题1:聚焦值读取修饰符不匹配
你在视图中通过.focusedSceneValue设置的是Scene级聚焦属性,需要使用对应的@FocusedSceneValue修饰符读取,你当前在TestCommands中使用的@FocusedValue仅用于读取普通视图级的.focusedValue属性,二者不匹配导致无法读到值。
修改后的TestCommands代码:
struct TestCommands: Commands { // 替换为@FocusedSceneValue修饰符 @FocusedSceneValue(\.action) var action var body: some Commands { CommandGroup(after: .newItem) { Button(action: { action?() }) { Text("Test menu item") } .disabled(action == nil) } } }
核心问题2:视图无聚焦能力导致值无法同步
macOS 中默认的Text视图不具备聚焦能力,无法进入响应链传递Scene级聚焦值,需要给视图添加.focusable()修饰符开启聚焦能力。
修改后的ContentView代码:
struct ContentView: View { var body: some View { Text("Hello, world!") .padding() // 新增开启视图聚焦能力 .focusable() .focusedSceneValue(\.action) { print("Clicked!") } } }
补充说明
你使用的Xcode 13 Beta 4、macOS Monterey Beta 4属于早期测试版本,存在SwiftUI API不稳定的已知问题,如果完成上述修改后仍有异常,可升级到正式版本验证。
内容的提问来源于stack exchange,提问作者newswiftuser
相关产品推荐
相关产品推荐

