Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI - Add Menu to navigationBarTrailing's ToolbarItem

Tags:

ios

swift

swiftui

I have a NavigationVeiw that has a ToolbarItem on the trailing side of its navigation-bar.

.toolbar {
    ToolbarItem(placement: .navigationBarTrailing) {
        Button(action: {}, label: {
            Text("Button")
        })
    }
}

navigationBarItems(leading:trailing:)is deprecated. Therefore, I am using toolbar(content:) with navigationBarTrailing placement. - Apple


I have used contextMenu on the Button.

   .toolbar {
        ToolbarItem(placement: .navigationBarTrailing) {
            Button(action: {}, label: {
                Text("Button")
            })
            .contextMenu(menuItems: {
                Text("Menu Item 1")
                Text("Menu Item 2")
                Text("Menu Item 3")
            })
        }
    }

It's not sensitive. You have to press hard to present it. I need to present it with a single touch like iOS Photo App's Add button. It is presented with a single touch.

How to show Menu with a single touch (not press)?

like image 467
mahan Avatar asked Jan 26 '26 08:01

mahan


2 Answers

.contextMenu is a 3D Touch (press and hold) just use a regular Menu

.toolbar {
     ToolbarItem(placement: .navigationBarTrailing) {
         Menu(content: {
             Text("Menu Item 1")
             Text("Menu Item 2")
              Text("Menu Item 3")
         }, label: {Text("button")})
      }
  }
like image 155
lorem ipsum Avatar answered Jan 28 '26 22:01

lorem ipsum


Since iOS 16, a ToolbarItemGroup can be given a label using init(placement:content:label:). When this is done:

A toolbar item group provided a label wraps its content within a ControlGroup which allows the content to collapse down into a menu that presents its content based on available space.

The style of menu can be determined by applying a .controlGroupStyle to the .toolbar:

.toolbar {
    ToolbarItemGroup(placement: .topBarTrailing) {
        Button("My option A", systemImage: "folder.badge.plus") {
            print("option A")
        }
        Button("My option B", systemImage: "doc.badge.plus") {
            print("option B")
        }
    } label: {
        Image(systemName: "plus")
            .imageScale(.large)
            .background(Color.red)
    }
}
.controlGroupStyle(.palette)

Animation

like image 30
Benzy Neez Avatar answered Jan 28 '26 21:01

Benzy Neez