问题
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