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

旧城冷巷雨未停 提交于 2020-05-29 04:04:10

问题


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?


回答1:


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())
        }
    }
}



回答2:


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




回答3:


Currently, you can't.

There are two overloads for .navigationBarTitle(), taking either a Text view or a type conforming to StringProtocol. You can't even pass in a modified view like Text("Title").font(.body). This would be a great feature, I'd submit a feature request: http://feedbackassistant.apple.com




回答4:


Try this...

How to put a logo in NavigationView in swiftui?

This shows how to handle adding an Image to NavigationView in SwiftUI. Hope it helps.



来源:https://stackoverflow.com/questions/58503322/swiftui-how-to-set-image-for-navigationbar-titleview-like-in-uikit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!