Chris
Chris

Reputation: 8091

appletv how to react on focus change event

i tried to change the textcolor of a button on AppleTV on focus change and this is my code (see below).

Unfortunately the code with if focus .. is never called. What am i doing wrong?

Thank you for any help!

struct ContentView: View {

    @State var textColor : Color = .white

    var body: some View {
        VStack {
            Button(action: {
                self.textColor = .black
            }) {
                Text("tap me")
            }
            .focusable(true) { (focus) in
                if focus {
                    self.textColor = .blue
                } else {
                    self.textColor = .green
                }
            }
            Button(action: {
                self.textColor = .black
            }) {
                Text("another tap me")
            }
            .focusable(true) { (focus) in
                if focus {
                    self.textColor = .blue
                } else {
                    self.textColor = .green
                }
            }
        }
    }
}

Upvotes: 1

Views: 225

Answers (1)

Asperi
Asperi

Reputation: 257711

The .focusable adds capability for elements non-focusable by nature, like Text (or Image), but Button is focusable as-is, so nothing happens.

The following modifications of your example works (tested with Xcode 11.2):

var body: some View {
    VStack {
        Text("Focusable").foregroundColor(textColor)
        .focusable(true) { (focus) in
            if focus {
                self.textColor = .blue
            } else {
                self.textColor = .green
            }
        }

        Button(action: {
            self.textColor = .black
        }) {
            Text("Button")
        }
    }
}

Upvotes: 2

Related Questions