'SwiftUI how to detect when a view has the focus?

I have two List's in a view and want to be able to determine which list currently has the focus in order to show the correct details of the selected item in the list in a details panel.

The following code never seems to get called, can anyone indicate whether there is another correct way to determine when focus changes.

struct StoreList: View {
    @EnvironmentObject private var database: Database
    @Binding var selectedStore: Store?

    var body: some View {
        List(selection: $selectedStore) {
            ForEach(database.stores, id: \.self) { store in
                StoreRow(store: store).tag(store)
                .focusable(true, onFocusChange:  { isFocused in
                    print("focus changed")
                        if isFocused {
                            self.database.selectedType = .store
                        }
                })
            }
        }
        .focusable(true, onFocusChange: { isFocused in
            print("focus changed")
                if isFocused {
                    self.database.selectedType = .store
                }
        })
    }
}

In the meantime I will explore detecting mouse clicks on the Rows since the user would need to click on an item in the list to move the focus.

Currently I am setting the selectedType value when an item changes (i.e. $selectedStore) in the view model (database) but if the user selected the already selected item in the other list then the value does not get updated but the List and list item does get the focus - well the visual colour change indicates it has the focus.

EDIT: I have also tried processing the onTapGesture callback which works fine except it replaces the List rows default behaviour. How can I make sure the event is passed through to the List as this might work then.



Solution 1:[1]

The easiest method of reacting to focus is

struct DummyView: View {
    @Environment(\.isFocused) var isFocused

    var body: some View {
        Text("My view")
        .padding()
        .background(isFocused ? Color.orange : Color.black)
    }
}

Sources

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

Source: Stack Overflow

Solution Source
Solution 1 Nasib