UIToolbar in SwiftUI
Table of Contents
In iOS 14, we finally have a way to set a toolbar for a view in a navigation view.
UIKit
In UIKIt, we can add toolbar items for a view controller under navigation stack by setting toolbarItems
with bar button items that you want. Then set isToolbarHidden = false
on a navigation controller that you wish to show a toolbar.
let archive = UIBarButtonItem(image: UIImage(systemName: "archivebox"), style: .plain, target: nil, action: nil)
let spacer = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let add = UIBarButtonItem(image: UIImage(systemName: "square.and.pencil"), style: .plain, target: nil, action: nil)
setToolbarItems([archive, spacer, add], animated: false) // <1>
navigationController?.isToolbarHidden = false // <2>
<1> Set toolbar items to a view controller.
<2> Set navigation controller to show toolbar.
SwiftUI
We can finally do this on iOS 14 with a new modifier in SwiftUI, toolbar()
, which lets us add a bar button just like we did in UIKit. By wrapping any view in ToolbarItem
and put that under toolbar
modifier, it will show up when that view embedded inside a NavigationView
.
NavigationView {
Text("Hello, SwiftUI!")
.toolbar {
ToolbarItem(placement: .bottomBar) {
Button(action: {}, label: {
Image(systemName: "archivebox")
})
}
ToolbarItem(placement: .bottomBar) {
Spacer()
}
ToolbarItem(placement: .bottomBar) {
Button(action: {}, label: {
Image(systemName: "square.and.pencil")
})
}
}
}
You can also group all the buttons inside a single ToolbarItem
like this:
NavigationView {
Text("Hello, SwiftUI!")
.toolbar {
ToolbarItem(placement: .bottomBar) {
HStack {
Button(action: {}, label: {
Image(systemName: "archivebox")
})
Spacer()
Button(action: {}, label: {
Image(systemName: "square.and.pencil")
})
}
}
}
}
You can easily support sarunw.com by checking out this sponsor.
AI Grammar: Correct grammar, spell check, check punctuation, and parphrase.
Related Resources
Read more article about SwiftUI, UIToolbar, Toolbar, WWDC20, or see all available topic
Enjoy the read?
If you enjoy this article, you can subscribe to the weekly newsletter.
Every Friday, you'll get a quick recap of all articles and tips posted on this site. No strings attached. Unsubscribe anytime.
Feel free to follow me on Twitter and ask your questions related to this post. Thanks for reading and see you next time.
If you enjoy my writing, please check out my Patreon https://www.patreon.com/sarunw and become my supporter. Sharing the article is also greatly appreciated.
Become a patron Buy me a coffee Tweet ShareCustom navigation bar title view in SwiftUI
Learn how to set a navigation bar title view in SwiftUI.
Cross-promote apps with SKOverlay
SKOverlay is a new tool from Apple for doing apps cross-promotion.