0

I'm trying to implement a textField that opens a menu style picker when you tap on it. One of the requirements is to be able to detect when the picker is opened/closed and perform custom actions to update the UI. This doesn't seem to be possible with SwiftUI. I'm wondering if it's possible to do this in Swift and wrap it with UIViewRepresentable for SwiftUI.

What I've have so far in SwiftUI:


    @State var options: [String] = ["Option 1", "Option 2", "Option 3"]
    @State var selectedOption: String = ""
    let placeholder: String = "Placeholder"

    Menu {
        Picker("Options", selection: selectedOption) {
            ForEach(options, id: \.self) { option in
                Text(option).tag(option)
            }
        }
        .onChange(of: selectedOption) { newValue in
            print("selected:\(newValue)") // <---Could only detect if an option is selected from picker
        }
    } label: {
        HStack {
            TextField(placeholder, text: $selectedOption)
                .disabled(true)
            Image(systemName: "chevron.down")
        }
        .padding(.horizontal, 16.0)
        .frame(height: 44.0)
    }

What the UI is supposed to look like:

enter image description here

When the textfield is clicked:

enter image description here

When commenting out Picker, the menu style picker is greyed out:

enter image description here

iamarnold
  • 705
  • 1
  • 8
  • 22
  • Do you have a screenshot of the intended design? This is difficult to follow, but if I had to guess you don't need the `Picker` simply remove it and leave the `ForEach` – xTwisteDx Aug 28 '23 at 21:17
  • Hi @xTwisteDx, I've added screenshots of the indented design. If I remove `Picker` in the code, the menu style dropdown options will be greyed out. The code is working right now and I'm able to select from the picker, but there's no way to detect when I first clicked on the textField to show the picker or when I click on outside the picker to dismiss it without selecting an option. – iamarnold Aug 29 '23 at 13:20

0 Answers0