问题描述
我遇到了一个持续数天的问题。我正在创建一个需要自定义导航链接(按钮)的 tvos 应用程序,当我将焦点移动到导航项时,它应该缩放一点,并且我还需要更改父级的视图背景。这很简单,但似乎 focusabe 覆盖了我的客户按钮样式。测试表明,当导航按钮获得焦点时,背景图像已更改但没有任何缩放效果。有什么建议吗?
NavigationLink(destination: Text("myview"))
{Text("Test")
}
.buttonStyle(myButtonStyle())
.Focusable(true){(focus) in
//the code to change the background image
//myButtonStyle deFinition
struct MyButtonStyle: ButtonStyle {
func makeBody(configuration: Configuration) -> some View {
return AppButton(configuration: configuration)
}
}
struct AppButton: View {
@Environment(\.isFocused) var focused: Bool
let configuration: ButtonStyle.Configuration
var body: some View {
configuration.label
.scaleEffect(focused ? 1.1 : 1.0)
.focusable(true)
}
}
当项目按我的预期获得焦点时,总是会调用更改背景图像的行,但缩放效果消失了。如果我删除以下代码行,缩放效果又回来了:
// .Focusable(true){(focus) in
//the code to change the background image
// }
看起来这行代码覆盖了我自定义的导航按钮样式,有什么想法吗?感谢您的帮助!
解决方法
啊,终于我发现了这个棘手的问题,虽然关于这个的文件很少。当Focusable 被引入时,它不应该在你的代码中改变焦点引擎,这会导致navigationlink tap 消息未被捕获,然后你的另一个视图的navigationlink 将不起作用。 使用 .onChange() 函数来处理任何焦点变化事件,而不是使用 Focusable。