每次我回到开始屏幕时,它似乎都会自动堆叠。您可以在所附的屏幕截图中看到我的意思。我添加了一些边框,以便您了解我的意思
“开始”屏幕的代码:
struct StartScreen: View {
var body: some View {
NavigationView{
VStack() {
Image("Headline").resizable().scaledToFit()
Image("GreenMonster")
.resizable()
.scaledToFit()
.frame(alignment: .top)
NavigationLink(destination: Game(monster: monster)) {
Text("Spielen")
.frame(width: 200, height: 50, alignment: .center)
.font(.title)
.padding()
.background(Color.blue)
.cornerRadius(40)
.foregroundColor(.white)
.padding(10)
.overlay(
RoundedRectangle(cornerRadius: 40)
.stroke(Color.blue, lineWidth: 5)
)
}.isDetailLink(false)
/*
NavigationLink(destination: Settings()){
Image("Settingswheel").resizable().scaledToFit().frame(width: 50, height: 50).offset(x: 150)
}
*/
}
}.navigationBarBackButtonHidden(true).border(Color.green)
}
}
,返回的代码是:
struct DefeatedView: View {
@EnvironmentObject var helper: Helper
var body: some View {
NavigationView(){
VStack(){
Text("BESIEGT!").foregroundColor(.green).font(.title).bold()
Image(monster[0].imageURL).resizable().scaledToFit()
NavigationLink(destination: StartScreen()){
Text("Zum Start").frame(width: 120, height: 6, alignment: .center)
.padding()
.background(Color.blue)
.cornerRadius(40)
.foregroundColor(.white)
.padding(10)
.overlay(
RoundedRectangle(cornerRadius: 40)
.stroke(Color.blue, lineWidth: 5)
)
}
}
}.navigationBarBackButtonHidden(true)
}
}
感谢我刚加入SwiftUI的帮助
答案 0 :(得分:1)
将此添加到您的DefeatedView
@Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
然后使用按钮将视图手动返回到起始视图,而不是再次使用NavigationLink
Button(action: {
//Push navigation view back
self.presentationMode.wrappedValue.dismiss()
})
{
Text("Zum Start").frame(width: 120, height: 6, alignment: .center)
.padding()
.background(Color.blue)
.cornerRadius(40)
.foregroundColor(.white)
.padding(10)
.overlay(
RoundedRectangle(cornerRadius: 40)
.stroke(Color.blue, lineWidth: 5)
)
}
编辑:
当您两次按下NavigationView
时,只调用一次演示模式便确实会回到您的游戏视图。这是ObservableObject
的可能解决方案。
class ViewHelper : ObservableObject
{
@Published var finishedGame : Bool = false
}
struct StartScreen: View {
@EnvironmentObject var viewHelper : ViewHelper
var body: some View {
NavigationLink(destination: Game(), isActive: self.$viewHelper.finishedGame) {
Text("Spielen")
然后,当游戏结束时,更改finishedGame
变量。
struct DefeatedView: View {
@EnvironmentObject var viewHelper : ViewHelper
var body: some View {
NavigationView(){
VStack(){
Text("BESIEGT!").foregroundColor(.green).font(.title).bold()
Button(action: {
self.viewHelper.finishedGame = false
})
{
Text("Zum Start").frame(width: 120, height: 6, alignment: .center)
.padding()
.background(Color.blue)
.cornerRadius(40)
.foregroundColor(.white)
.padding(10)
.overlay(
RoundedRectangle(cornerRadius: 40)
.stroke(Color.blue, lineWidth: 5)
)
}
}
}.navigationBarBackButtonHidden(true)
答案 1 :(得分:0)
我在此站点上找到了解决问题的方法: