How to put checkmark when Menu item selected SwiftUI

2.3k Views Asked by At

Im trying to put checkmark when menu item selected.I tried give a @State var selectedSort : Int = .zero and give id(selectedSort) but It didn't work. How can I solve this problem ?

This is my code;

struct SortMenuPickerView : View {

@Binding var sortClicked : Bool
@ObservedObject var productListViewModel = ProductListViewModel()
@State var sortListArray : [ProductListSortAndFilterList]
var function: () -> Void
@Binding var sortId : String

var body : some View {
    
    HStack(alignment: .center){
        
        Spacer()
        
        Menu {
            
            ForEach(sortListArray,id:\.id){ item in
                if item.id == "sort" {
                    
                    ForEach(item.sortList ?? [],id:\.id) { data in
                        
                        Button(action: {
                            
                            sortId = (data.id ?? "")
                            
                            self.function()
                            
                            print("selected item is : \(data.id!)")
                            
                            
                        }) {
                            
                            Text(data.name ?? "")
                                .tag(data.id)
                            
                        }
                    }
                }
            }
        } label: {
            
            SortView()
            
        }
1

There are 1 best solutions below

0
On

Try with picker style menu & can customise with your requirements...

Its sample example:

@State private var sort: Int = 0

var body: some View {
    NavigationView {
        Text("Hello World!")
        .toolbar {
            ToolbarItem(placement: .primaryAction) {
                Menu {
                    Picker(selection: $sort, label:Text("Sortingoptions")) {
                        Text("Sort1").tag(0)
                        Text("Sort2").tag(1)
                        Text("Sort3").tag(2)
                    }
                }
                label: {
                    Text("Sort")
                }
            }
        }
    }
}