我正在使用SwiftUI在tvOS上测试一些东西。当我给一个按钮添加自定义样式时,按钮的“动作”不会被触发。在这个例子中,我想要打印“pressed”,但添加函数也不起作用。
是否可能实现自定义操作触发器,或者我做错了什么?
为了说明我为什么想要自定义按钮样式。
当我不使用任何按钮样式时,“动作”可以正常工作,但“onFocusChange”函数从未被调用。我需要它!
但是……当我使用一个按钮样式时,“onFocusChange”可以工作,但是“动作”却不能……
struct CustomButton: View {
@State private var buttonFocus: Bool = false
var body: some View {
VStack(alignment: .center){
Button(action: {
print("pressed")
})
{
Text("Save")
}
.buttonStyle(TestButtonStyle(focused: buttonFocus))
.focusable(true, onFocusChange: { (changed) in
self.buttonFocus.toggle()
})
}
}
}
按钮样式:
struct TestButtonStyle: ButtonStyle {
let focused: Bool
public func makeBody(configuration: TestButtonStyle.Configuration) -> some View {
configuration.label
.foregroundColor(.white)
.background(RoundedRectangle(cornerRadius: 5).fill(Color.red))
.scaleEffect(focused ? 1.5 : 1.0)
}
}