SwiftUI tvOS按钮/ NavigationLink .focusable

问题描述

我有一个直接跨平台的SwiftUI项目。而且在tvOS上与supplier.account = account 一起工作很困难。

(下面的所有内容都是伪代码,可能是拼写错误

以它为例,这很好用:

NavigationLink

我的要求是,当您在列表中滑动时,背景图像会随着焦点项目的变化而变化。

现在,我想要要做的就是这个。但是,在struct ContentView: View { var body: some View { NavigationView { ScrollView(.horizontal) { HStack { ForEach(items) { item in NavigationLink(destination: DetailView(item: item)) { Card(item: item) } } } } } } } 上覆盖.focusable()似乎会禁用其点击操作。

NavigationLink

到目前为止,我已经尝试过:

我认为自己会很聪明,可以使用动态的NavigationLink,并创建一个可聚焦的按钮来为我设置标签。结果相同:(

struct ContentView: View {
  // Store Focused Item
  @State private var currentItem: Item?

  var body: some View {
    NavigationView {
      ScrollView(.horizontal) {
        HStack {
          ForEach(items) { item in
            NavigationLink(destination: DetailView(item: item)) {
              Card(item: item)
            }
            // Set which item is highlighted
            .focusable(true) { isFocused in
              currentItem = item
            }
          }
        }
      }
    }
  }
}

**问题**

  1. 可以在仍struct ContentView: View { @State private var currentItem: Item? // Store Selection Tag @State private var selection: String? = nil var body: some View { // ... NavigationLink(destination: DetailView(item: item),tag: item.title,selection: $selection) { EmptyView() } Button(action: { selection = item.title }) { Card(item: item) } .buttonStyle(PlainButtonStyle()) .focusable(true) { isFocused in currentItem = item } // ... } } 调用操作的位置进行配置吗?
  2. 有什么办法报告当前关注的项目吗?

感谢您的帮助。这似乎很简单,但是我已经走到尽头了。

解决方法

我找到了答案。那是因为在引入 Focusable 时,它​​将打破当前的焦点引擎状态。为了更好地控制焦点行为,请不要使用focusable,请使用.onchange 作为焦点更改触发事件。