'Allow SwiftUI view to detect tvOS menu button presses

I am currently building an app for tvOS is Swift and am getting a tad stuck. The majority of the app has been coded using SwiftUI. However, I now need to add a Gesture Recogniser to allow each page to pickup button presses from the remote control.

I have these two files, one of which is a gesture recogniser which picks up menu button presses, and the other which controls the app's navigation:

//
//  AppNavigator.swift
//

import SwiftUI

struct NavigationItem {
    var view: AnyView
}

final class NavigationStack: ObservableObject {
    @Published var viewStack: [NavigationItem] = []
    @Published var currentView: NavigationItem
    
    init(_ currentView: NavigationItem ) {
        self.currentView = currentView
    }
    
    @objc func pop() {
        if viewStack.count == 0 {
            return
        }
        let last = viewStack.count - 1
        currentView = viewStack[last]
        viewStack.remove(at: last)
    }
    
    func push(_ view: NavigationItem) {
        viewStack.append(currentView)
        currentView = view
    }
}

struct NavigationHost: View {
    @EnvironmentObject var navigation: NavigationStack

    var body: some View {
        self.navigation.currentView.view
    }
}
//
//  MenuButtonGesture.swift
//

import UIKit

class MenuButtonGestureRecogniser: UIGestureRecognizer {
    
    override func reset() {
      if state == .possible {
        state = .failed
      }
    }
    
    override func pressesBegan(_ presses: Set<UIPress>, with event: UIPressesEvent) {
        guard let press = presses.first else {
            return
          }
        if press.type == .menu {
            state = .recognized
        }        
    }
    
    override func pressesCancelled(_ presses: Set<UIPress>, with event: UIPressesEvent) {
        reset()
    }
    
    override func pressesEnded(_ presses: Set<UIPress>, with event: UIPressesEvent) {
        reset()
    }
}

My aim is to pop the current view each time the menu button is pressed, but I can't find anything in SwiftUI about tvOS button presses, hence why my custom gesture recogniser is done in UIKit.

If anyone could give me some pointers if I'm missing something, or tell me how I could convert my navigator to work with the gesture recogniser that would be great. Note that the rest of the app is in SwiftUI (the view in each instance of NavigationItem), so any changes would need to work with that.

Preferably, the solution would involve using the gesture recogniser in the swiftUI code but I understand that probably wont be the case.

Thanks



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source