Put an image in NavigationView in SwiftUI
In this tutorial, we’ll learn how to put an image in the Navigation view of SwiftUI. We can give an image to the navigation view in SwiftUI using navigationBarItems. NavigationBarItems lets us give an image or any other view to the leading side as well as the trailing side of the navigation view in SwiftUI.
What this blog will cover:
- How to put an image in the NavigationView of SwiftUI.
- navigationBarTitle.
- navigationBarItems.
Let’s put an image in NavigationView in SwiftUI.
struct ContentView: View { var body: some View { Text("Hello World") } }
So this is our mainView
, ContentView which only contains a single TextView right now. Embed ContentView’s content in a NavigationView.
Give the NavigationView
a title using navigationBarTitle
.
struct ContentView: View { var body: some View { NavigationView { Text("hello World") .navigationBarTitle(Text("Navigation Bar"),displayMode: .inline) } } }
– Trailing Image:
Let’s put an image to the trailing side of the NavigationView in SwiftUI using the modifier navigationBarItems. All you have to do is give the trailing parameter of navigationBarItems
an image or we can give it any other view as well. It will appear on the trailing side of the NavigationView.
struct ContentView: View { var body: some View { NavigationView { Text("hello World") .navigationBarTitle(Text("Navigation Bar"),displayMode: .inline) // give image to the trailing end .navigationBarItems(trailing:Image(systemName: "magnifyingglass")) } } }
– Leading Image:
Now Let’s give an image on the leading side of the NavigationView. Give the leading parameter of navigationBarItems
an image.
struct ContentView: View { var body: some View { NavigationView { Text("hello World") .navigationBarTitle(Text("Navigation Bar"),displayMode: .inline) //give image to the trailing end .navigationBarItems(leading: Image(systemName: "arrow.left")) } } }
– Image to both ends Leading and trailing:
We can give the image to both ends leading and trailing at the same time. Just give value to both the leading and trailing parameters of navigationBarItems
.
struct ContentView: View { var body: some View { NavigationView { Text("hello World") .navigationBarTitle(Text("Navigation Bar"),displayMode: .inline) // give image to the both ends .navigationBarItems( leading:Image(systemName: "arrow.left") , trailing:Image(systemName:"magnifyingglass") ) } } }
Leave a Reply