问题描述
我正在尝试使用徽标图像代替该应用程序顶部的NavigationView标题.在NavigationView中找不到有关使用图像的任何文档.
I am trying to use a logo image instead of a NavigationView title at the top section of the app. Couldn't find any documentation of using images inside a NavigationView.
推荐答案
NavigationView.navigationBarTitle()
现在只能 接受Text()
自变量.您可以改用.navigationBarItems()
将Image
设置为trailing
或leading
参数,但这与UINavigationItem.leftBarButtonItem[s]
和UINavigationItem.rightBarButtonItem[s]
的SwiftUI等效,这意味着您只能使用导航栏按钮尺寸.但是,如果您对此没问题,则可能需要设置一个空白标题,以便可以指定标准高度的导航栏.
NavigationView.navigationBarTitle()
can only take a Text()
argument right now. You could instead use .navigationBarItems()
to set an Image
as either the trailing
or leading
argument, but this is the SwiftUI equivalent of UINavigationItem.leftBarButtonItem[s]
and UINavigationItem.rightBarButtonItem[s]
, which means that you're restricted to navigation bar button dimensions. But if you're ok with that, you may want to set a blank title so that you can specify a standard-height navigation bar.
如果您可以忍受自己的生活,则可以 通过对图像周围的填充进行硬编码来伪造居中的导航栏项目,例如
If you can stand to live with yourself, you can fake a centered nav bar item by hard-coding padding around the image, like
.padding(.trailing, 125),
(请注意,我故意将其偏心放置,以便您可以看到它是硬编码的.)
(Note that I deliberately positioned it off-center so that you can see that it's hard-coded.)
如果您知道所使用图像的确切宽度,则最好将整个内容包装在GeometryReader { geometry in ... }
块中以使用屏幕尺寸来计算精确的位置:
Even better would be to wrap the whole thing in a GeometryReader { geometry in ... }
block to use the screen dimensions to calculate precise positioning, if you know the exact width of the image you're using:
GeometryReader { geometry in
NavigationView {
...
}
.navigationBarTitle(Text(""), displayMode: .inline)
.navigationBarItems(trailing:
PresentationButton(
Image(systemName: "person.crop.circle")
.imageScale(.large)
.padding(.trailing, (geometry.size.width / 2.0) + -30), // image width = 60
destination: ProfileHost()
)
)
如果您不想对其进行黑客入侵,可以执行以下操作:
If you don't want to hack it, here's what you can do:
.navigationBarTitle(Text(""), displayMode: .inline)
.navigationBarItems(leading:
PresentationButton(
Image(systemName: "person.crop.circle")
.imageScale(.large)
.padding(),
destination: ProfileHost()
)
)
.navigationBarTitle(Text(""), displayMode: .inline)
.navigationBarItems(trailing:
PresentationButton(
Image(systemName: "person.crop.circle")
.imageScale(.large)
.padding(),
destination: ProfileHost()
)
)
.navigationBarItems(leading:
PresentationButton(
Image(systemName: "person.crop.circle")
.imageScale(.large)
.padding(),
destination: ProfileHost()
)
)
这篇关于如何在SwiftUI的NavigationView中放置徽标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!