Button is not selectable on tvOS using own ButtonStyle in SwiftUI

≡放荡痞女 提交于 2020-06-16 06:20:13

问题


After replacing a standard button style with a custom one, the button isn't selectable anymore on tvOS (it works as expected on iOS). Is there a special modifier in PlainButtonStyle() that I'm missing? Or is it a bug in SwiftUI?

Here's the snipped that works:

Button(
    action: { },
    label: { Text("Start") }
).buttonStyle(PlainButtonStyle())

and here's the one that doesn't:

Button(
    action: { },
    label: { Text("Start") }
).buttonStyle(RoundedButtonStyle())

where RoundedButtonStyle() is defined as:

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

回答1:


If you create your own style you have to handle focus manual. Of course there are different ways how you could do this.

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

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


来源:https://stackoverflow.com/questions/58178439/button-is-not-selectable-on-tvos-using-own-buttonstyle-in-swiftui

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!