Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI how to set image for NavigationBar titleView like in UIKit?

I want to set an image in the titleView of NavigationBar in SwiftUI, as we do in UIKit

navigationItem.titleView = UIImageView(image: UIImage(named: "logo"))

this is how we do it in UIKit.

anyone know how to do it?

like image 360
Zeeshan Ahmed Avatar asked Oct 22 '19 11:10

Zeeshan Ahmed


2 Answers

Here's how to do it:

  1. Add SwiftUIX to your project.
  2. Set your custom title view via View.navigationBarTitleView(_:displayMode:)

Example code:

struct ContentView: View {
    public var body: some View {
        NavigationView {
            Text("Hello World")
                .navigationBarTitleView(MyView())
        }
    }
}
like image 186
Vatsal Manot Avatar answered Sep 20 '22 18:09

Vatsal Manot


Simple, Just add your root view into ZStack with top alignment and add your custom center view after root view

struct CenterNavigattionBar: View {
    var body: some View {
        ZStack(alignment: .top){
            //Root view with empty Title
            NavigationView {
                Text("Test Navigation")
                .navigationBarTitle("",displayMode: .inline)
                .navigationBarItems(leading: Text("Cancle"), trailing: Text("Done"))
            }
            //Your Custom Title
            VStack{
                Text("add title and")
                    .font(.headline)
                Text("subtitle here")
                    .font(.subheadline)
            }
        }

    }
}

Before Image

1

After Image

2

like image 23
Jitesh Bharadiya Avatar answered Sep 19 '22 18:09

Jitesh Bharadiya