Search code examples
iosarraysswiftswiftuiswiftui-list

How to display the selected menu item in SwiftUI?


I want to selected menu to get displayed and saved when the user comes back later. my current code just displays the selected item, but not getting saved when I close the sheet and comes back.


  @State var selectedAge: Int = .zero
  
  var body: some View {
    Menu {
      ForEach(myViewModel.MyModel.selectAge.indices, id: \.self) { indice in
        Button(action: {
          selectedAge = indice
        }) {
          if selectedAge == indice {
            Text("\(myViewModel.MyModel.selectAge[indice])")
          }
          else {
            Text("")
          }
        }
      }
    } label: {
      Text("\(myViewModel.MyModel.selectAge[selectedAge])")
    }
  }

This code from my Model

var selectedAge: [String] = ["12", "15", "18", "21", "24"]

Please guide me to solve this issue.


Solution

  • I used this code to solve my issue.

    Menu {
        ForEach(myViewModel.myModel.selectAge, id: \.self) { index in
            Button {
                myViewModel.myModel.selectAge = "\(index)"
            } {
                if myViewModel.myModel.selectedAge == index {
                    Label("\(index)", systemImage: "checkmark")
                } else {
                    Text("\(index)")
                }
            }
        }
    } label: {
        Text("\(myViewModel.myModel.selectedAge)")
    }
    
    

    and this is insert in my model

    var selectedAge = "12"
    var selectedAge: [String] = ["12", "15", "18", "21", "24"]