使用 SwiftUI 在 tvOS 上测试一些东西。当我向按钮添加自定义样式时,按钮的“ Action ”没有被触发。在此示例中,我想打印“按下”,但添加功能也不起作用。
是否也可以实现自定义操作触发器或者我做错了什么?
为了澄清为什么我想要自定义按钮样式。
当我不使用任何按钮样式时,“操作”正在运行,但“onFocusChange”函数永远不会被调用。我需要什么!
但是..当我使用 buttonstyle 时,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)
}
}
最佳答案
它现在可以与 SwiftUI 2.0 一起使用。 您可以在要关注的 View 上使用以下环境对象。 此外,添加一个 State 或 Binding 以冒泡到您的父 View 。
@Environment(\.isFocused) var isFocused: Bool
@Binding var focusedValue: Bool
然后,您可以调用以下修饰符,它会在 View 获得焦点或未获得焦点时调用。您可以在此处更改 Binding 或 State 变量。
.onChange(of: isFocused, perform: { value in
self.focusedValue = value
})
最后,您可以使用您的绑定(bind)或状态来修改您的 View 。
.scaleEffect(self.focused ? 1.1 : 1)
.animation(.linear(duration: 0.1))
关于xcode - SwiftUI:未触发自定义按钮的操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61523595/