在 SwiftUI 中使用自己的 ButtonStyle 在 tvOS 上无法选择按钮

G. *_*arc 6 tvos swiftui

将标准按钮样式替换为自定义按钮样式后,该按钮在 tvOS 上不再可选(它在 iOS 上按预期工作)。PlainButtonStyle() 中是否有我缺少的特殊修饰符?或者这是 SwiftUI 中的一个错误?

这是有效的截图:

Button(
    action: { },
    label: { Text("Start") }
).buttonStyle(PlainButtonStyle())
Run Code Online (Sandbox Code Playgroud)

这是一个没有的:

Button(
    action: { },
    label: { Text("Start") }
).buttonStyle(RoundedButtonStyle())
Run Code Online (Sandbox Code Playgroud)

其中 RoundedButtonStyle() 定义为:

struct RoundedButtonStyle: ButtonStyle {
    func makeBody(configuration: Configuration) -> some View {
        configuration.label
            .padding(6)
            .foregroundColor(Color.white)
            .background(Color.blue)
            .cornerRadius(100)
    }
}
Run Code Online (Sandbox Code Playgroud)

Mar*_* T. 2

如果您创建自己的风格,则必须手动处理焦点。当然,您可以通过不同的方式来做到这一点。

struct RoundedButtonStyle: ButtonStyle {

    let focused: Bool
    func makeBody(configuration: Configuration) -> some View {
        configuration
            .label
            .padding(6)
            .foregroundColor(Color.white)
            .background(Color.blue)
            .cornerRadius(100)
            .shadow(color: .black, radius: self.focused ? 20 : 0, x: 0, y: 0) //  0

    }
}
Run Code Online (Sandbox Code Playgroud)
struct ContentView: View {

    @State private var buttonFocus: Bool = false
    var body: some View {
        VStack {
            Text("Hello World")

            Button(
                action: { },
                label: { Text("Start") }
            ).buttonStyle(RoundedButtonStyle(focused: buttonFocus))
                .focusable(true) { (value) in
                    self.buttonFocus = value
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 谢谢你,我错过了修饰符“.focusable(true)”。现在可以聚焦按钮,但不幸的是,按钮的操作永远不会被触发。知道原因是什么吗? (5认同)
  • 有人有解决方案吗?同样的问题 (5认同)