在 SwiftUI (tvOS) 中获取按钮的 onFocusChange 回调

2024-03-22

The onFocusChange关闭于focusable(_:onFocusChange:)修饰符允许我在子视图聚焦时为父视图设置属性,如下所示:

struct ContentView: View {
    @State var text: String
    var body: some View {
        VStack {
            Text(text)
            Text("top")
                .padding()
                .focusable(true, onFocusChange: { focused in
                    text = "top focus"
                })
            Text("bottom")
                .padding()
                .focusable(true, onFocusChange: { focused in
                    text = "bottom focus"
                })
        }
        
    }
}

但在 2020 年 WWDC 视频中focusable引入时,明确指出该包装器不打算与本质上可聚焦的视图(例如按钮和列表)一起使用。如果我在这里使用按钮代替文本,则 onFocusChange 可以工作,但按钮的正常焦点行为会中断:

struct ContentView: View {
    @State var text: String
    var body: some View {
        VStack {
            Text(text)
            Button("top") {}
                .padding()
                .focusable(true, onFocusChange: { focused in
                    text = "top focus"
                })
            Button("bottom") {}
                .padding()
                .focusable(true, onFocusChange: { focused in
                    text = "bottom focus"
                })
        }
        
    }
}

是否有任何通用方法可以让 onFocusChange 闭包与按钮一起使用,而不会破坏其正常的可聚焦行为?或者还有其他方法可以实现这一点吗?


尝试使用@Environment(\.isFocused) and .onChange(of:perform:)在 ButtonStyle 中:

struct ContentView: View {
    var body: some View {
          Button("top") {
             // button action
          }
          .buttonStyle(MyButtonStyle())
    }
}

struct MyButtonStyle: ButtonStyle {
    @Environment(\.isFocused) var focused: Bool

    func makeBody(configuration: Configuration) -> some View {
        configuration.label
            .onChange(of: focused) { newValue in
                // do whatever based on focus
            }
    }
}

IIRC 使用@Environment(\.isFocused)ButtonStyle 内部可能仅适用于 iOS 14.5+,但您可以创建自定义 View 而不是 ButtonStyle 以支持旧版本。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 SwiftUI (tvOS) 中获取按钮的 onFocusChange 回调 的相关文章

随机推荐