Home > OS >  SwiftUI Add TextField to Menu
SwiftUI Add TextField to Menu

Time:10-14

I have a menu and want to be able to input some data from the menu. This is what I've tried and it shows up in the menu, but doesn't allow any input. Is there a way to hack some input in SwiftUI Menus?

                  Menu("Award Users") {
                        TextField(awardedAmount, text: $awardedAmount)
                        
                        Button("Send") {
                            
                        }
                    }

CodePudding user response:

SwiftUI will simplify the layout of the menu items, and if not possible, it may discard some of your items. Not all views are suitable to work as a menu item and they will be silently ignored. These are some of the views that work: Menu, Text, Button, Link, Label, Divider or Image.

CodePudding user response:

SwiftUI Menu gives us a dedicated view for showing popup button with the help of menus. Menu option is used to create variety of buttons to control what you want to appear in the menu. If you add a textfield, Menu View will consider it as button title and disable its action as shown in image below.

enter image description here

struct ContentView: View {
    
    @State private var awardedAmount = "125"
    
    var body: some View {
        VStack{
            Menu("Options") {
                TextField(awardedAmount, text: $awardedAmount)
                Button("Order Now", action: placeOrder)
                Button("Adjust Order", action: adjustOrder)
                Button("Cancel", action: cancelOrder)
            }
            
        }
    }
    
    func placeOrder() { }
    func adjustOrder() { }
    func cancelOrder() { }
}

So in short Menu is a dedicated view for buttons for selecting an option, not taking user inputs.

  • Related