onFocusChange 未在 SwiftUI tvOS 中触发

onFocusChange not triggered in SwiftUI tvOS

我正在尝试设置 onFocusChange 并在视图上单击操作功能。但是 onFocusChange 永远不会被调用。

ScrollView(.horizontal, showsIndicators: false) {
    HStack(alignment: .center, spacing: 5) {
        ForEach(self.videos, id: \.id) { video in
            
            Button(action: {
                print("clicked")
            }){
                ItemView(vid: video)
                    .cornerRadius(5).padding(1)
            }.focusable(true, onFocusChange: {
                hasFocus in
                print("focused")
            })
        }
    }
}

如果我将按钮视图移动到 ItemView() 中,onFocusChange 有效但点击操作无效。

问题的目标尚不清楚,但这里有一个简单的演示,说明使用自定义按钮样式管理焦点和按钮单击的替代方法。也许这会有所帮助。

已使用 Xcode 12 / tvOS 14(模拟器)进行测试 - 比较常规按钮与自定义按钮

struct MyButtonStyle: ButtonStyle {
    func makeBody(configuration: Configuration) -> some View {
        configuration.label
            .scaleEffect(configuration.isPressed ? 1.2 : 1)
    }
}

struct ContentView: View {
    @State private var focused = false
    var body: some View {
        VStack {
            Button(action: {
                print(">>>> custom button")
            }) { LabelView() }.buttonStyle(MyButtonStyle())

            Button("Regular Button") {
                print(">> regular button")
            }
        }
    }
}

struct LabelView: View {
    @Environment(\.isFocused) var focused: Bool
    var body: some View {
        RoundedRectangle(cornerRadius: 25.0)
            .frame(width: 200, height: 100)
            .foregroundColor(focused ? .blue : .gray)
            .overlay(Text("Title").foregroundColor(.white))
    }
}