为什么滚动功能在 Apple TV 中不起作用?

问题描述 投票:0回答:1

我在滚动视图中有 LazyHGrid 但它不滚动。我尝试了多种选择,但不幸的是没有成功。

 ScrollView(.horizontal) {
            LazyHStack {
                ForEach(1..<20) { index in
                    Text("Item \(index)")
                        .padding()
                        .foregroundColor(.white)
                        .background(Color.blue)
                        .cornerRadius(10)
                        .padding(.horizontal, 5)
                        .focusable() // Ensure each item is focusable
                }
            }
            .frame(height: 200) // Adjust height as needed
            .padding()
        }
        .padding()
swiftui scrollview tvos apple-tv lazyhgrid
1个回答
0
投票

我做了一些研究,发现滚动实际上可以在 tvOS 上运行,但由于我们使用遥控器来在元素之间切换,因此我们需要以不同的方式与内容进行交互。

因此,在使用模拟器时,您应该使用键盘上的箭头在元素之间切换。所以在你的情况下你会使用 ⏴ & ⏵。

您将看到滚动确实有效,但无法了解当前选择了哪个元素。因此,您可以使用 @FocusState 属性并检查其值来更改所选单元格的背景颜色。

struct ContentView: View {
    @FocusState var selectedItem: Int?
    
    var body: some View {
        ScrollView(.horizontal) {
            LazyHStack {
                ForEach(1..<20) { index in
                    Text("Item \(index)")
                        .padding()
                        .foregroundColor(.white)
                        .background(selectedItem == index ? Color.blue.opacity(0.6) : Color.blue )
                        .cornerRadius(10)
                        .padding(.horizontal, 5)
                        .focusable()// Ensure each item is focusable
                        .focused($selectedItem, equals: index) // Add this line!
                }
            }
            .frame(height: 200) // Adjust height as needed
            .padding()
        }
        .padding()
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.