有没有一种方法可以在SwiftUI的ZStack中保持视图始终可见?
我有一个观点,我想在某个时候完全涵盖,我只希望一个特定的儿童观点不被涵盖。这在SwiftUI中可能吗 请参见以下代码示例:有没有一种方法可以在SwiftUI的ZStack中保持视图始终可见?,swiftui,Swiftui,我有一个观点,我想在某个时候完全涵盖,我只希望一个特定的儿童观点不被涵盖。这在SwiftUI中可能吗 请参见以下代码示例: import SwiftUI @main struct ZIndexExperimentApp: App { var body: some Scene { WindowGroup { ContentView() } } } struct ContentView: View { @State
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
}
})
}
}
有没有办法使第二个
文本
位于封面上方?我试图将其上的zindex
设置为一个高值,但似乎没有效果。我认为使用foregroundColor或hidden是更好的方法,因为如果你在屏幕上删除一些视图,你会注意到视图上的一些位移,这对用户来说是不愉快的
第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 } }
}
}
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 } }
}
}
第2版:
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 } }
}
}
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 } }
}
}
使用隐藏似乎是一个很好的替代品。谢谢