ios - onFocusChange 在 SwiftUI tvOS 中未触发

标签 ios swift swiftui tvos

我正在尝试设置 onFocusChange 并在 View 上单击操作函数。但是 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() 内移动按钮 View ,onFocusChange 会起作用,但单击操作不会。

最佳答案

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

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

enter image description here

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))
    }
}

关于ios - onFocusChange 在 SwiftUI tvOS 中未触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63171417/

相关文章:

ios - 什么时候调用委托(delegate)?

ios - 如何在 UI 测试中加载动画后检查元素是否存在? swift

ios - 将 BindableObject 传递给 View

swift - 为什么我不能返回一个从声明为 "-> () -> some View"的 Swift 函数返回 View 的闭包?

ios - 在 Swift 中以编程方式突出显示 UITableViewCell

ios - UIImage 的高质量缩放

ios - 更改属性值为 True 的 UITableViewCell 文本颜色

ios - SwiftUI 中具有可变数量选项卡的自定义选项卡栏

ios - 启动画面时间可以配置吗?

ios - 滚动时保持 UITableViewCell 可见? ( swift 3)