无法通过 SwiftUI 中的 @State 绑定变量切换视图

时间:2021-05-19 23:03:06

标签: swift swiftui swiftui-state

我试图在视图文件之间传递一个状态变量以在视图之间导航,但它似乎不起作用。当按下注册按钮时,“view”变量会更新,但它不会改变视图。这是我目前实施方式的简化版本:

import SwiftUI
import FireBaseAuth

struct ContentView: View {
    @State private var view = "Main"
    
    var body: some View {
        
        if Auth.auth().currentUser?.uid == nil {
            LoginView(view: $view)
        }
        else if view == "Register" {
            RegisterView(view: $view)
        }
        else {
            MainView()
        }
    }
}

登录查看

import SwiftUI

struct LoginView: View {
    @Binding var view: String
    var body: some View {
        
        return VStack(content: {
            
            Button(
                action: {
                    view = "Register"
                    print(view)
                },
                label: {
                    Text("Register")
                })
            
        })
        
    }
}

注册查看

import SwiftUI

struct RegisterView: View {
    @Binding var view: String
    var body: some View {
        Text("Hi!")
        Button("Back", action: {
            view = "Login"
        })
    }
}

0 个答案:

没有答案