且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

以编程方式导航到 SwiftUI 中的新视图

更新时间:2023-12-04 21:28:22

您可以在登录成功后用您的登录视图替换下一个视图.例如:

You can replace the next view with your login view after a successful login. For example:

struct LoginView: View {
    var body: some View {
        ...
    }
}

struct NextView: View {
    var body: some View {
        ...
    }
}

// Your starting view
struct ContentView: View {

    @EnvironmentObject var userAuth: UserAuth 

    var body: some View {
        if !userAuth.isLoggedin {
            LoginView()
        } else {
            NextView()
        }

    }
}

您应该在您的数据模型中处理您的登录过程,并使用诸如 @EnvironmentObject 之类的绑定将 isLoggedin 传递给您的视图.

You should handle your login process in your data model and use bindings such as @EnvironmentObject to pass isLoggedin to your view.

注意:在 Xcode Version 11.0 beta 4 中,为了符合协议 'BindableObject'willChange 必须添加属性

Note: In Xcode Version 11.0 beta 4, to conform to protocol 'BindableObject' the willChange property has to be added

import Combine

class UserAuth: ObservableObject {

  let didChange = PassthroughSubject<UserAuth,Never>()

  // required to conform to protocol 'ObservableObject' 
  let willChange = PassthroughSubject<UserAuth,Never>()

  func login() {
    // login request... on success:
    self.isLoggedin = true
  }

  var isLoggedin = false {
    didSet {
      didChange.send(self)
    }

    // willSet {
    //       willChange.send(self)
    // }
  }
}