iosiphoneswiftuiswiftui-pickerswiftui-menu

SwiftUI Picker in Menu


I want to display the selection when using a picker in menu like in the reminders app for Sort By and I cannot for the life of me figure out how to do it.

This is what I want:

https://i.sstatic.net/Lwm2R.jpg

This is my code:

private func menuButton() -> some View {
    Menu {
        Menu {
            Picker(selection: $group, label: Text("Grouping options")) {
                Text("None").tag(0)
                Text("Type").tag(1)
            }
        } label: {
            Label("Group By", systemImage: "square.grid.3x1.below.line.grid.1x2")
        }
        Menu {
            Picker(selection: $sort, label: Text("Sorting options")) {
                Text("Name").tag(0)
                Text("Priority").tag(1)
            }
        } label: {
            Label("Sort By", systemImage: "arrow.up.arrow.down")
        }
        Divider()
        Button {
            toggleInbox()
        } label: {
            Label(inboxList?.isHidden == false ? "Hide Inbox" : "Show Inbox", systemImage: inboxList?.isHidden == false ? "eye.slash" : "eye")
        }
    } label: {
        Image(systemName: "ellipsis.circle.fill")
            .font(.custom("Button", size: 22))
            .foregroundStyle(.blue, Color(UIColor.systemGray5))
    }
}

Solution

  • Use a Button as the label for your Menu (see Swiftui: multiple lines in a menu item or picker):

    Menu {
        Picker(selection: $sort, label: Text("Sorting options")) {
            Text("Name").tag(0)
            Text("Priority").tag(1)
        }
    } label: {
        Button(action: {}) {
            Text("Sort by")
            Text(sort == 0 ? "Name" : "Priority")
            Image(systemName: "arrow.up.arrow.down")
        }
    }
    

    Another hint: you can use .pickerStyle(.menu) on your Picker, so you don't have to wrap it in a Menu.