SwiftUI:自定义按钮的操作未触发

时间:2020-04-30 12:39:37

标签: xcode button swiftui tvos apple-tv

使用SwiftUI在tvOS上测试一些东西。当我向按钮添加自定义样式时,不会触发按钮的“动作”。在此示例中,我想打印“按下”,但是添加功能也不起作用。

是否还可以实现自定义操作触发器,或者我在做什么错呢?

为弄清为什么我要具有自定义按钮样式。

当我不使用任何按钮样式时,“操作”有效,但是从未调用“ 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)
    }
}

1 个答案:

答案 0 :(得分:0)

它现在可以与SwiftUI 2.0一起使用。 您可以在要聚焦的视图上使用以下环境对象。 另外,添加“状态”或“绑定”以冒泡至父视图。

@Environment(\.isFocused) var isFocused: Bool
@Binding var focusedValue: Bool

然后,您可以调用以下修饰符,该修饰符在View是否获得焦点时被调用。在这里,您可以更改Binding或State变量。

.onChange(of: isFocused, perform: { value in
        self.focusedValue = value
    })

最后,您可以使用“绑定”或“状态”来修改视图。

.scaleEffect(self.focused ? 1.1 : 1)
.animation(.linear(duration: 0.1))