SwiftUI: Problem with Picker inside ContextMenu of NavigationBarItem

Viewed 103

I'm trying to use Picker on .contextMenu of navigationBarItems. However, the behavior is not as I would expect and I can't tell if this is Apple bug or if I'm doing something wrong (XCode 13.4). After the user selects an item from the dropdown, the variable value do change but reopening the context menu, the wrong item is marked as "selected".

I've created the most basic demo to illustrate it. Same behavior on real device (iPhone 11 / iOS 15.4.1).

struct ContentView: View {
    @State private var isAutoRefresh = true

    var body: some View {
        NavigationView {
            Text("Auto refresh is: \(String(isAutoRefresh))")
                .navigationBarTitle("Demo")
                .navigationBarItems(
                    trailing:
                        Button(action: {}, label: {
                            Image(systemName: "arrow.clockwise")
                        })
                        .contextMenu {
                            Picker(selection: self.$isAutoRefresh, label: Text("")) {
                                Text("Manual refresh").tag(false)
                                Text("Auto refresh").tag(true)
                            }
                            .pickerStyle(InlinePickerStyle())
                        }
                )
        }
    }
}

enter image description here

Is this a bug? Is there any workaround I can use?

1 Answers

Context menu is created once and cached, so we need to rebuild it once anything changed outside.

Here is a fix. Tested with Xcode 13.3 / iOS 15.4

.contextMenu {
    Picker(selection: self.$isAutoRefresh, label: Text("")) {
        Text("Manual refresh").tag(false)
        Text("Auto refresh").tag(true)
    }
    .pickerStyle(InlinePickerStyle())
}.id(isAutoRefresh)                    // << here !!

Alternate: Just to use Menu instead of Button with context menu (if applicable by design), like

Menu {
         Picker(selection: self.$isAutoRefresh, label: Text("")) {
              Text("Manual refresh").tag(false)
              Text("Auto refresh").tag(true)
         }
         .pickerStyle(InlinePickerStyle())
    } label: {
         Image(systemName: "arrow.clockwise")
    }
Related