1

SwiftUI Toolbar Title Menus

 1 year ago
source link: https://useyourloaf.com/blog/swiftui-toolbar-title-menus/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

SwiftUI Toolbar Title Menus

SwiftUI Toolbar Title Menus

Jan 16, 2023 · 2 minute read

How do you add custom actions to the toolbar title menu?

Navigation Title Menu

We’ve seen how you can rename the navigation title by passing a binding to .navigationTitle. That gives you a drop-down menu from the toolbar with a single rename action:

Navigation bar with drop down menu with rename action

How do we add other actions to that drop-down menu?

Toolbar Title Menus

Here’s my toolbar setup from the earlier example with save and cancel buttons:

.toolbar {
  ToolbarItem(placement: .primaryAction) {
    Button("Save") { ... }
  }
  ToolbarItem(placement: .cancellationAction) {
      Button("Cancel", role: .cancel) { ... }
  }
}

You can add a title menu with your own custom actions by adding the ToolbarTitleMenu to the toolbar:

.toolbar {
  ToolbarItem(placement: .primaryAction) { ... }
  ToolbarItem(placement: .cancellationAction) { ... }

  ToolbarTitleMenu {
    FavButton()
    ClearButton()
  }
}

On iOS and iPadOS that gives you a menu that drops-down from the navigation title in the toolbar:

Title menu with favorite and clear actions

Note though that I’ve lost the ability to rename the title. To get the rename action back you need to include the RenameButton in the list of buttons in the toolbar title menu:

ToolbarTitleMenu {
  FavButton()
  RenameButton()
  ClearButton()
}

That gives me back the rename action together with my custom actions:

Title menu with favorite, rename, and clear actions

Documentation Bugs

A word or warning if you’re watching the WWDC22 video SwiftUI on iPad: Add toolbars, titles, and more. That video shows a, now out-of-date, code snippet for adding actions to the title menu:

PlaceDetailContent(place: $place)
  // toolbar customizations ...
  .navigationTitle(place.name) {
    MyPrintButton()
    RenameButton
 }

Apple removed that method of passing the menu actions in a closure to the navigation title modifier during the iOS 16 betas. I don’t expect Apple to change WWDC videos. Unfortunately, the documentation for the RenameButton still has a similar example (FB11944833).

Never Miss A Post

Sign up to get my iOS posts and news direct to your inbox and I'll also send you a PDF of my WWDC 2022 Viewing Guide

WWDC 2022 Viewing Guide

Unsubscribe at any time. See privacy policy.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK