Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

ios - onFocusChange not triggered in SwiftUI tvOS

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

ScrollView(.horizontal, showsIndicators: false) {
    HStack(alignment: .center, spacing: 5) {
        ForEach(self.videos, id: .id) { video in
            
            Button(action: {
                print("clicked")
            }){
                ItemView(vid: video)
                    .cornerRadius(5).padding(1)
            }.focusable(true, onFocusChange: {
                hasFocus in
                print("focused")
            })
        }
    }
}

If I move the button view inside the ItemView(), the onFocusChange works but the click action doesn't.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

enter image description here

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))
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...