Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI update State on Navigation Action

I am using a Navigation View in my SwiftUI Mac OSX app. I have having a List view to select Persons, and then display their attributes in PersonDetail. It is working fine. However, I am sending a State to a Binding in PersonDetail View.

That is working fine, however everytime a new row is clicked, I want to reset my State s_selectedView to 0 again.

Is there an event for NavigationView updates? I tried using a onAppear() event in my PersonDetail view, however that is only called once. The only option I see is pushing my State towards my List and then change it on the tapGesture of the Table View.

That is my Navigation View code:

  NavigationView {
    PersonList(selectedPerson: $selectedPerson)

    if selectedPerson != nil {
        PersonDetail(person: selectedPerson!, s_currentView: self.$s_selectedView)
        //Here I would need a event, for appear / update
        //.onAppear
        //{
            //only called once 
        //}

    }
  }

This is my binding in the same view above:

@State var s_selectedView : Int = 0

I want to reset that variable to 0, whenever a new item was pressed in the list.

TL:DR

Is there a equivalent function like onAppear only for update for a state? The problem is that my view is not appearing again (onAppear is not getting called), just the data is changing due to @State event. How can I catch that event?

like image 702
davidev Avatar asked Oct 28 '22 01:10

davidev


1 Answers

You can try something like the following - use proxy binding to selected person and once selected person changed reset your state:

(scratchy - not tested)

NavigationView {
    PersonList(selectedPerson: Binding<Type_Of_Selected_Person>(get: {
            self.selectedPerson
        }, set: {
            self.selectedPerson = $0
            self.s_selectedView = 0
        }))
like image 166
Asperi Avatar answered Nov 01 '22 01:11

Asperi