将标准按钮样式替换为自定义按钮样式后,该按钮在tvOS上不再可用(在iOS上可以正常使用)。我缺少PlainButtonStyle()中的特殊修饰符吗?还是SwiftUI中的错误?
以下是有效的片段:
Button(
action: { },
label: { Text("Start") }
).buttonStyle(PlainButtonStyle())
这是没有的:
Button(
action: { },
label: { Text("Start") }
).buttonStyle(RoundedButtonStyle())
其中RoundedButtonStyle()定义为:
struct RoundedButtonStyle: ButtonStyle {
func makeBody(configuration: Configuration) -> some View {
configuration.label
.padding(6)
.foregroundColor(Color.white)
.background(Color.blue)
.cornerRadius(100)
}
}
答案 0 :(得分:0)
如果创建自己的样式,则必须处理焦点手册。当然,有多种方法可以实现此目的。
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
}
}
}
}
答案 1 :(得分:0)
我已经以这种方式完成了它,并且工作正常,您需要做的只是处理聚焦状态。
struct AppButtonStyle: ButtonStyle {
let color: Color = .clear
func makeBody(configuration: Configuration) -> some View {
return AppButton(configuration: configuration, color: color)
}
struct AppButton: View {
@State var focused: Bool = false
let configuration: ButtonStyle.Configuration
let color: Color
var body: some View {
configuration.label
.foregroundColor(.white)
.background(RoundedRectangle(cornerRadius: 20).fill(color))
.compositingGroup()
.shadow(color: .black, radius: 5)
.scaleEffect(focused ? 1.1 : 1.0)
.padding()
.focusable(true) { focused in
withAnimation {
self.focused = focused
}
}
}
}
}
当按钮聚焦时,我只是在缩放它,您可以按照相同的想法做其他事情,所以假设您不想更改背景颜色:
.background(RoundedRectangle(cornerRadius: 20).fill(focused ? .red : .white))
要使用:
struct SomeView: View {
var body: some View {
NavigationView {
NavigationLink(
destination: Text("Destination")) {
Text("Hi")
}
.buttonStyle(AppButtonStyle())
.padding()
}
}
}