c_b*_*oth 3 focus tvos focus-engine swiftui
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"
})
}
}
}
Run Code Online (Sandbox Code Playgroud)
但在 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"
})
}
}
}
Run Code Online (Sandbox Code Playgroud)
是否有任何通用方法可以让 onFocusChange 闭包与按钮一起使用,而不会破坏其正常的可聚焦行为?或者还有其他方法可以实现这一点吗?
尝试在 ButtonStyle 中使用@Environment(\.isFocused)
and :.onChange(of:perform:)
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
}
}
}
Run Code Online (Sandbox Code Playgroud)
@Environment(\.isFocused)
在 ButtonStyle 内部使用 IIRC可能仅适用于 iOS 14.5+,但您可以创建自定义 View 而不是 ButtonStyle 以支持旧版本。
归档时间: |
|
查看次数: |
2655 次 |
最近记录: |