Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI: Creating a Pull-down menu

in the HIG Apple writes: In iOS 14 and later, a button can display a pull-down menu that lists items or actions from which people can choose

This is exactly what I want for my project. This picture where they have a "more" bar button with a drop-down menu fits the bill perfectly. Does anyone have an example, though, of how to create a pull-down menu (not context-menu) from a button with SwiftUI?

like image 518
niklassaers Avatar asked Dec 07 '22 10:12

niklassaers


1 Answers

You can simply use the Menu view that is new for iOS in iOS 14.

It acts as a button and when pressed presents the context menu. You can use a Label if you want an image and even nest different views, as shown in the example in the documentation.

struct ContentView: View {
    @State var text = "Hello World"
    
    var body: some View {
        NavigationView {
            Text("Hello World")
                .navigationTitle("Hello")
                .navigationBarItems(trailing: {
                    Menu {
                        Button(action: { text = "Hello there" }) {
                            Label("Hello", systemImage: "pencil")
                        }
                    } label: {
                        Image(systemName: "ellipsis.circle")
                    }
                    
                }())
        }
        .navigationViewStyle(StackNavigationViewStyle())
    }
}

Instead of navigationBarItems one should probably use toolbar, however I found that to be quite unreliable starting with Beta 4.


An example menu

like image 162
jlsiewert Avatar answered Dec 22 '22 21:12

jlsiewert