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

标签 xcode button swiftui tvos apple-tv

使用 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/

相关文章:

swiftui - @EnvironmentObject 通过 navigationLink 不能很好地工作

swift - NavigationLink isActive 在 navigationBarItems 中不起作用(尾随 :) modifier

objective-c - Xcode 在哪里存储 3rd 方 API secret /密码/id

objective-c - NSRunAlertPanel 和超链接

xcode - 如何在 Swift 应用程序中访问声音文件

android - 无法在android studio中小写按钮文本

java - 警报对话框无法正常运行。

python - 在没有 GoogleService-Info.plist 的情况下将调试符号上传到 Crashlytics

java - Android 通过单击按钮删除动态创建的微调器和按钮

ios - SwiftUI NavigationLink push in onAppear 使用@ObservableObject 时立即弹出 View