问题
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:
- Add SwiftUIX to your project.
- 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
After Image
回答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