如何获取ContentView的背景图像,而不是其子视图,并保留可滚动内容在NavBar下消失的行为?
我发现,如果我将背景作为修饰符添加到列表或ScrollView中,它不会更改子视图(例如)上的背景。DetailView),但是可滚动的内容不再消失在导航栏下,navbar标题保持不变(见图2)。但是如果我修改了NavigationView,它恢复了滚动内容在导航栏下消失的行为(见图3),但它也改变了所有子视图的背景(见图4)。
我尝试了一个ZStack和图像(“MoonPhoto”),然后列表
但大多数情况下,我尝试了这个ViewModifier结构的不同位置:
struct BackgroundImage: ViewModifier {
func body(content: Content) -> some View {
content
.opacity(0.8)
.background(Image("history-in-hd-e5eDHbmHprg-unsplash")
.resizable()
.scaledToFill())
}
}以下是ContentView的主体:
var body: some View {
NavigationView {
List(missions) { mission in
NavigationLink(destination: MissionView(mission: mission, astronauts: self.astronauts))
{
Image(mission.image)
.resizable()
.scaledToFit()
.frame(width: 50, height: 50)
VStack(alignment: .leading) {
Text(mission.displayName)
.font(.headline)
Text(self.showCrew ? self.crewList(mission: mission) : mission.formattedLaunchDate)
}
}
.navigationBarTitle("Moonshot")
}
.navigationBarTitle("Moonshot")
.navigationBarItems(leading:
Button(self.showCrew ? "Show Launch date" : "Show crew") {
self.showCrew.toggle()
}
)
.modifier(BackgroundImage()) //Modifying List
} //If you move the above modifier here, the image shows an all subviews too
}
}


发布于 2019-11-05 17:21:15
我观察到的主要问题是关于.large DisplayMode for navigationBarTitle修饰符的。我找到了一个适合我自己的解决方案,但这还是一个解决办法。不管怎样,你可以把它看作是一个临时的解决方案。
其主要思想是在VStack中封装列表,并使用.inline显示模式。希望这能帮上忙。
下面是它的外观(也适用于黑暗模式)

import SwiftUI
struct BackgroundImage: ViewModifier {
func body(content: Content) -> some View {
content
.opacity(0.8)
.background(Image("history-in-hd-e5eDHbmHprg-unsplash")
.resizable()
.scaledToFill())
}
}
struct ContentView: View {
var body: some View {
NavigationView {
VStack {
List (1...20, id: \.self) { value in
NavigationLink(destination: Text("Details \(value)")) {
Text("\(value)")
}
}
}
.modifier(BackgroundImage())
.navigationBarTitle("Title", displayMode: .inline)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}https://stackoverflow.com/questions/58701184
复制相似问题