onFocusChange not triggered in SwiftUI tvOS

前端 未结 1 345
-上瘾入骨i
-上瘾入骨i 2021-01-16 19:39

I am trying to set onFocusChange and click action function on a view. But onFocusChange is never called.



        
相关标签:
1条回答
  • 2021-01-16 20:44

    The goal the question is unclear, but here is a simple demo of alternate approach to have managed focused & button click using custom button style. Maybe this will be helpful.

    Tested with Xcode 12 / tvOS 14 (Simulator) - compare regular button vs custom button

    struct MyButtonStyle: ButtonStyle {
        func makeBody(configuration: Configuration) -> some View {
            configuration.label
                .scaleEffect(configuration.isPressed ? 1.2 : 1)
        }
    }
    
    struct ContentView: View {
        @State private var focused = false
        var body: some View {
            VStack {
                Button(action: {
                    print(">>>> custom button")
                }) { LabelView() }.buttonStyle(MyButtonStyle())
    
                Button("Regular Button") {
                    print(">> regular button")
                }
            }
        }
    }
    
    struct LabelView: View {
        @Environment(\.isFocused) var focused: Bool
        var body: some View {
            RoundedRectangle(cornerRadius: 25.0)
                .frame(width: 200, height: 100)
                .foregroundColor(focused ? .blue : .gray)
                .overlay(Text("Title").foregroundColor(.white))
        }
    }
    
    0 讨论(0)
提交回复
热议问题