Creating a SwiftUI Toolbar and Adding Menus
In this tutorial, you will learn how to create a toolbar in SwiftUI and add various types of menus to it. The toolbar is a standard UI element that can be found in many iOS, iPadOS, and macOS applications, and it provides quick access to frequently used actions.
You will learn how to customize the appearance of the toolbar, add various types of menus such as contextual, pop-up, and drop-down menus, and how to respond to user interactions with these menus.
By the end of this tutorial, you will have a clear understanding of how to create a toolbar in SwiftUI and how to add different types of menus to it.
Use the Toolbar modifier to place multiple items in the navigation bar or bottom bar
Using the Toolbar in SwiftUI, you have more control over the placement of your navigation buttons such as the navigation bar or bottom bar.
Additionally, these action items will adapt accordingly to iOS, iPadOS, watchOS, macOS and tvOS.
Navigation View Toolbar
- The toolbar modifier can only be placed inside a NavigationView.
- By default, it will act the same way as NavigationBarItems, but you get more options like placement and group.
NavigationView {
Text("My app")
.toolbar {
ToolbarItem {
Image(systemName: "person.crop.circle")
}
}
}
ToolbarItem Placement
- By default, the toolbar will be placed in the navigation bar.
- But you also have other placements: bottomBar, cancellationAction, confirmationAction, destructionAction, navigation, navigationLeading, navigationTrailing.
- Each placement will adapt to its respective platform.
ToolbarItem(placement: .bottomBar) {
Button(action: {}) {
Image(systemName: "person.crop.circle")
}
}
..
ToolbarItemGroup
For all placements except navigation and automatic, you can insert multiple elements.
ToolbarItemGroup(placement: .confirmationAction) {
Image(systemName: "person")
Image(systemName: "ellipsis")
}
..
If it's a bottomBar placement, you have even more control over the items. You can use Spacer to push the elements.
ToolbarItemGroup(placement: .bottomBar) {
Image(systemName: "person")
Spacer()
Image(systemName: "ellipsis")
Spacer()
Image(systemName: "trash")
}
..
Sample code:
NavigationView {
Text("My app")
.toolbar {
ToolbarItemGroup(placement: .bottomBar) {
Image(systemName: "person")
HStack {
Image(systemName: "ellipsis")
Divider()
Image(systemName: "trash")
.frame(width: 32, height: 32)
.background(Color.blue)
.mask(Circle())
}
}
}
..
Comments
Post a Comment