有没有一种方法可以让视图在SwiftUI中的ZStack中始终可见



我有一个视图,我想在某个时候完全覆盖它,我只想不覆盖一个特定的子视图。这在SwiftUI中可能吗?

参见此代码示例:

import SwiftUI
@main
struct ZIndexExperimentApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
struct ContentView: View {
@State var showCover = false
var body: some View {
ZStack {
VStack {
Spacer()
Text("Normal text")
.font(.headline)
.padding()
Text("Text that should always be visible")
.font(.headline)
.padding()
Spacer()
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.edgesIgnoringSafeArea(.all)
if self.showCover {
VStack {
Rectangle()
.fill(Color.blue)
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
.edgesIgnoringSafeArea(.all)
}
}
.onAppear(perform: {
DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
self.showCover = true
}
})
}
}

有没有办法让第二个Text位于封面的顶部?我试图将其上的zindex设置为一个高值,但似乎没有效果。

我认为使用foregroundColor或隐藏是更好的方法,因为如果你在屏幕上杀死一些视图,你会注意到视图上的一些位移,这对用户来说并不愉快。


版本1:

import SwiftUI
struct ContentView: View {

@State var showCover: Bool = Bool()

var body: some View {

ZStack {

if showCover { Color.blue }

VStack {

Spacer()

Text("Normal text")
.foregroundColor(showCover ? Color.clear : Color.primary)
.padding()

Text("Text that should always be visible")
.padding()

Spacer()
}

}
.font(.headline)
.ignoresSafeArea()
.onAppear() { DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(3)) { showCover = true } }

}
}

版本2:

import SwiftUI
struct ContentView: View {

@State var showCover: Bool = Bool()

var body: some View {

ZStack {

if showCover { Color.blue }

VStack {

Spacer()

if showCover { Text("Normal text").padding().hidden() }
else { Text("Normal text").padding() }

Text("Text that should always be visible")
.padding()

Spacer()
}

}
.font(.headline)
.ignoresSafeArea()
.onAppear() { DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(3)) { showCover = true } }

}
}

最新更新