PopUp don't want to dismiss SwiftUI - swift

I am having a problem while I want to dismiss a popup (that appears automatically depending on a specific condition) by clicking a button.
This is the PopUp struct:
struct dataPrivacyPopUp: View {
let model: OffersView.Model
let termsOfUseText = "Nutzungsbedingungen"
let privacyPolicyText = "Datenschutzerklärung"
#State var termsOfUseChecked = false
#State var privacyPolicyChecked = false
#State var buttonDisabled = true
#State private var showPopUp: Bool = false
#Binding var showModal: Bool
var body: some View {
ZStack {
if ( model.showPopUp == true) {
// PopUp Window
VStack(alignment: .center){
Image("logo")
.aspectRatio(contentMode: .fill)
.frame(alignment: .center)
.padding()
VStack(alignment: .leading) {
Text((model.acceptance?.salutation)!)
.multilineTextAlignment(.leading)
.padding()
.foregroundColor(Color.black)
Text((model.acceptance?.statement)!)
.multilineTextAlignment(.leading)
.padding()
.foregroundColor(Color.black)
Text((model.acceptance?.declarationIntro)!)
.multilineTextAlignment(.leading)
.padding()
.foregroundColor(Color.black)
if ((model.acceptance?.dpr)! == true) {
VStack(alignment: .leading){
HStack {
CheckBoxView(checked: $privacyPolicyChecked)
HStack(spacing: 0){
Text(R.string.localizable.dataPrivacyPopupText())
.foregroundColor(Color.black)
Button(privacyPolicyText) {
model.openUrl(url: API.privacyPolicyURL)
}
}
}
Text((model.acceptance?.declarationOutro)!)
.multilineTextAlignment(.leading)
.padding()
}
.padding()
Button(action: {
model.setTos()
print("showModal PopUpView2 1: \(showModal)")
self.showModal.toggle()
print("showModal PopUpView2 2: \(showModal)")
}, label: {
Text(R.string.localizable.dataPrivacyButton())
.foregroundColor(Color.white)
.font(Font.system(size: 23, weight: .semibold))
})
.disabled(model.buttonDisabledForOne(privacyPolicyChecked: privacyPolicyChecked, termsOfUseChecked: termsOfUseChecked))
.padding()
}
}
}
// .onAppear(perform: )
.background(Color.white01)
.padding()
}
}
}
}
and this is where I call it (contentView):
struct OffersView: View {
#StateObject var model = Model()
#State private var showingPopUp = false
#State private var showModal = false
#State private var showingAddUser = false
// var showPopup : Bool = true
var body: some View {
NavigationView {
Group {
switch model.sections {
case .loading:
ActivityIndicator(animate: true)
case .success(let sections):
ScrollView(.vertical) {
VStack(alignment: .leading, spacing: 0) {
Text(R.string.localizable.offersHello(model.firstName))
.aplFont(.headline02)
.padding(.bottom, 24)
VStack(spacing: 48) {
ForEach(sections) { section in
OffersSectionView(section: section, model: model)
}
}
}
.useFullWidth(alignment: .leading)
.padding()
}
default:
Color.clear
if ( model.showPopUp == true) {
ZStack {
Color.black.opacity(model.showPopUp ? 0.3 : 0).edgesIgnoringSafeArea(.all)
dataPrivacyPopUp(model: model, showModal: self.$showModal)
.onAppear(perform: {
self.showModal.toggle()
})
}
}
}
}
.navigationBarHidden(true)
.handleNavigation(model.navigationPublisher)
.onAppear(perform: model.onAppear)
.onDisappear(perform: model.onDisappear)
.environment(\.dynamicTypeEnabled, false)
.safariView(isPresented: model.showSafari) {
SafariView(url: model.safariUrl!)
}
}
}
}
I need help about this, I tried the traditional method to set a #Binding variable etc .. but that's not working, the boolean value is changing but the UI is not updating (the popup is not dismissing), thank you

I tried to look at your code - I suggest you simplify it to the bare minimum to exemplify your issue - and it seems that you are using 2 properties to show your pop-up: showingPopUp and showModal. It is quite likely that you are having trouble keeping them both in sync.
For starters, I would suggest to use only one variable, either it is true or false - "a man with two watches never knows what time it is".
For the solution:
If you prefer keeping your ZStack approach, the solution would look something like:
struct MyPrivacy: View {
#Binding var showMe: Bool
var body: some View {
VStack {
Text("The content of the pop-up")
.padding()
Button {
withAnimation {
showMe.toggle()
}
} label: {
Text("Dismiss")
}
}
}
}
struct Offers: View {
#State private var showPopup = false
var body: some View {
NavigationView {
ZStack {
VStack {
Text("View behind the pop-up")
.padding()
Button {
withAnimation {
showPopup.toggle()
}
} label: {
Text("Pop")
}
}
if showPopup {
Color.white
MyPrivacy(showMe: $showPopup)
}
}
}
}
}
If instead you want to go for a more flexible approach, if you are developing for iOS, SwiftUI has a convenient object - Sheets. You can use it as suggested in the documentation, or build a specific struct that manages all the modal views of this type and use your model to handle the presentation.
The process goes like:
Create a struct that will handle all kinds of Sheets of your app.
Add to your view-model the property to present any sheet.
Create the Views that will be the content of each sheet.
Call the .sheet(item:content:) method on each View the requires a sheet.
Here's the sample code:
SheetView handler:
struct SheetView: Identifiable {
// This struct controls what modal view will be presented.
// The enum SheetScreenType can grow to as many as different
// modal views your app needs - add the content in the switch below.
let id = UUID()
var screen: SheetScreenType
#ViewBuilder
var content: some View {
switch screen {
case .dataPrivacy:
DataPrivacy()
default:
EmptyView()
}
}
enum SheetScreenType {
case dataPrivacy
case none
}
}
Presenter in your view-model:
class MyViewModel: ObservableObject {
// This code can fit anywhere within your view-model.
// It controls the presentation of the modal view, which in
// this case is a Sheet.
private let sharedSheet = SheetView(screen: .none)
// Show the selected sheet
#Published var sheetView: SheetView?
var showSheet: SheetView.SheetScreenType {
get {
return sheetView?.screen ?? .none
}
set {
switch newValue {
case .none:
sheetView = nil
default:
sheetView = sharedSheet
}
sheetView?.screen = newValue
}
}
}
Content of your modal view:
struct DataPrivacy: View {
#EnvironmentObject var model: MyViewModel // Pass YOUR model here
var body: some View {
VStack(alignment: .center){
Text("Respecting your privacy, no details are shown here")
.padding()
Button {
print("Anything you need")
// Set the showSheet property of your model to
// present a modal view. Setting it to .none dismisses
// the modal view.
model.showSheet = .none
} label: {
Text("Time do dismiss the modal view")
}
.padding()
}
}
}
Enable your view to listen to your model to present the sheet:
struct OffersView: View {
#ObservedObject var model = MyViewModel() // Pass YOUR model here
var body: some View {
VStack {
Text("Anything you wish")
.padding()
Button {
withAnimation {
// Set the showSheet property of your model to
// present a modal view. Set it to any choice
// among the ones in the SheetScreen.SheetScreenType enum.
model.showSheet = .dataPrivacy
}
} label: {
Text("Tap here for the privacy in modal view")
}
}
// Show a modal sheet.
// Add this property at the top level of every view that
// requires a modal view presented - whatever content it might have.
.sheet(item: $model.sheetView) { sheet in
sheet.content
.environmentObject(model)
}
}
}
Good luck with your project!

Related

Navigation stack yellow warning triangle

I'm attempting to listen for a change in a boolean value & changing the view once it has been heard which it does successfully, however, results in a yellow triangle. I haven't managed to pinpoint the issue but it doesn't seem to have anything to do with the view that it's transitioning to as even when changed the error still persists.
My code is below
import SwiftUI
struct ConversationsView: View {
#State var isShowingNewMessageView = false
#State var showChat = false
#State var root = [Root]()
var body: some View {
NavigationStack(path: $root) {
ZStack(alignment: .bottomTrailing) {
ScrollView {
LazyVStack {
ForEach(0..<20) { _ in
Text("Test")
}
}
}.padding()
}
Button {
self.isShowingNewMessageView.toggle()
} label: {
Image(systemName: "plus.message.fill")
.resizable()
.renderingMode(.template)
.frame(width: 48, height: 48)
.padding()
.foregroundColor(Color.blue)
.sheet(isPresented: $isShowingNewMessageView, content: {
NewMessageView(show: $isShowingNewMessageView, startChat: $showChat)
})
}
}
.onChange(of: showChat) { newValue in
guard newValue else {return}
root.append(.profile)
}.navigationDestination(for: Root.self) { navigation in
switch navigation {
case .profile:
ChatView()
}
}
}
enum Root {
case profile
}
}
ChatView() Code:
import SwiftUI
struct ChatView: View {
#State var messageText: String = ""
var body: some View {
VStack {
ScrollView {
VStack(alignment: .leading, spacing: 12) {
ForEach(MOCK_MESSAGES) { message in
MessageView(message: message)
}
}
}.padding(.top)
MessageInputView(messageText: $messageText)
.padding()
}
}
}
Any support is much appreciated.
You should use navigationDestination modifier inside your NavigationStack component, just move it.
NavigationStack(path: $root) {
ZStack(alignment: .bottomTrailing) {
ScrollView {
LazyVStack {
ForEach(0..<20) { _ in
Text("Test")
}
}
}.padding()
}.navigationDestination(for: Root.self) { navigation in
switch navigation {
case .profile:
ChatView()
}
}
//...
}
Basically this yellow triangle means NavigationStack can't find suitable component for path. And when you using navigationDestination directly on NavigationStack View or somewhere outside it is ignored
You must set .environmentObject(root) to NavigationStack in order to provide the NavigationPath to the view subhierarchy (ChatView in your case). Also you must have a #EnvironmentObject property of type Root in your ChatView so that it can read the path.

Open sheet and overwrite current sheet or provide internal navigationstack inside sheet

So I have a button as shown below:
private var getStartedButton: some View {
Button {
showGetStartedSheet.toggle()
} label: {
Text("Get Started")
}
.sheet(isPresented: $showGetStartedSheet) {
LoginUserSheetView()
.presentationDetents([.fraction(0.70), .large])
}
}
Which opens the LoginUserSheetView() view and has the following function inside:
private var userCreateAccount: some View {
VStack(alignment: .center) {
Text("New MapGliders? User register")
.sheet(isPresented: $showUserRegisterSheet) {
RegisterUserSheetView()
.presentationDetents([.fraction(0.70), .large])
}
}
}
The above code, then opens another sheet which presents the following code:
private var appleButton: some View {
Button {
// Hello
} label: {
HStack(alignment: .firstTextBaseline) {
Image(systemName: "applelogo")
Text("Hello")
}
}
}
The above code (lots has been removed) produces the following output:
https://im4.ezgif.com/tmp/ezgif-4-4ecfdb6d55.gif
As you can see the video above, the second sheet opens on top of the old sheet, I would like the sheet to be overwritten or create a navigation on a single sheet.
Does anyone know how I can close LoginUserSheetView() when RegisterUserSheetView() is opened? or how could I make the sheet be overwritten or even use a navigation to navigate to RegisterUserSheetView() when on the LoginUserSheetView() is opened.
The first option is to use sheet(item:). But this does dismiss the sheet and they makes it reappear with the new value
struct DynamicOverlay: View {
#State var selectedOverlay: OverlayViews? = nil
var body: some View {
VStack{
Text("hello there")
Button("first", action: {
selectedOverlay = .first
})
}
.sheet(item: $selectedOverlay){ passed in
passed.view($selectedOverlay)
}
}
enum OverlayViews: String, Identifiable{
var id: String{
rawValue
}
case first
case second
#ViewBuilder func view(_ selectedView: Binding<OverlayViews?>) -> some View{
switch self{
case .first:
ZStack {
Color.blue
.opacity(0.5)
Button {
selectedView.wrappedValue = .second
} label: {
Text("Next")
}
}
case .second:
ZStack {
Color.red
.opacity(0.5)
Button("home") {
selectedView.wrappedValue = nil
}
}
}
}
}
}
The second option doesn't have the animation behavior but required a small "middle-man" View
import SwiftUI
struct DynamicOverlay: View {
#State var selectedOverlay: OverlayViews = .none
#State var presentSheet: Bool = false
var body: some View {
VStack{
Text("hello there")
Button("first", action: {
selectedOverlay = .first
presentSheet = true
})
}
.sheet(isPresented: $presentSheet){
//Middle-main
UpdatePlaceHolder(selectedOverlay: $selectedOverlay)
}
}
enum OverlayViews{
case first
case second
case none
#ViewBuilder func view(_ selectedView: Binding<OverlayViews>) -> some View{
switch self{
case .first:
ZStack {
Color.blue
.opacity(0.5)
Button {
selectedView.wrappedValue = .second
} label: {
Text("Next")
}
}
case .second:
ZStack {
Color.red
.opacity(0.5)
Button("home") {
selectedView.wrappedValue = .none
}
}
case .none:
EmptyView()
}
}
}
//Needed to reload/update the selected item on initial presentation
struct UpdatePlaceHolder: View {
#Binding var selectedOverlay: OverlayViews
var body: some View{
selectedOverlay.view($selectedOverlay)
}
}
}
You can read a little more on why you need that intermediate view here SwiftUI: Understanding .sheet / .fullScreenCover lifecycle when using constant vs #Binding initializers

Binding a button leads to "Missing argument for parameter in call" error

I'm trying to create a Binding in two views so I can change something on one side and have it reflected on the other.
I basically have:
a circle on both views
a button to change the other view's circle color
and one to go to the other view
It all works fine if I only have a Binding in the "ColorChange2"
view, but when I add a Binding in "ColorChange1" I get into trouble.
It tells me: Missing argument for parameter 'isOn2'.
But when I add isOn2 into ColorChange1() it wants a binding, but if I do ColorChange1(isOn2: $isOn2) it says it can't find '$isOn2' in scope.
I found one solution suggesting to add .constant(true)) into the preview but since it's a constant, it wont change the view like I wanted since it's a constant.
What can I do to make it work?
Code:
struct ColorChange1: View {
#State private var isOn = false
#Binding var isOn2 : Bool
var body: some View {
NavigationView {
VStack {
Circle()
.fill(isOn ? .green : .red)
.frame(width: 100)
Button(action: {
isOn2.toggle()
}, label: {
Text("Change button view 2")
.padding()
})
NavigationLink(destination: {
ColorChange2(isOn: $isOn)
}, label: {
Text("Go to view 2")
})
}
}
}
}
struct ColorChange2: View {
#Binding var isOn : Bool
#State private var isOn2 = false
#Environment(\.dismiss) var dismiss
var body: some View {
VStack {
Circle()
.fill(isOn2 ? .green : .red)
.frame(width: 100)
Button(action: {
isOn.toggle()
}, label: {
Text("Change button view 1")
.padding()
})
Button(action: {
dismiss.callAsFunction()
}, label: {
Text("Go to view 1")
})
}
.navigationBarBackButtonHidden(true)
}
}
struct ColorChange_Previews: PreviewProvider {
static var previews: some View {
// ColorChange(isOn2: .constant(true))
ColorChange1()
}
} ```
You don't need both #Binding value in both screen to connect between screen like that.
#Binding means that get the value in #State of the first view and make a connection in the second view. In this scenero, when you go back from second view, it was dismissed.
For your problem, make an ObservableObject to store value. 1 for present in first view and 1 for second view. Then add it to second view when ever you need to display.
Code will be like this
class ColorModel : ObservableObject {
#Published var isOnFirstView = false
#Published var isOnSecondView = false
func didTapChangeColor(atFirstView: Bool) {
if atFirstView {
isOnSecondView = !isOnSecondView
} else {
isOnFirstView = !isOnFirstView
}
}
}
struct ColorChange2: View {
// binding model
#ObservedObject var colorModel : ColorModel
#Environment(\.dismiss) var dismiss
var body: some View {
VStack {
Circle()
.fill(colorModel.isOnSecondView ? .green : .red)
.frame(width: 100)
Button(action: {
colorModel.didTapChangeColor(atFirstView: false)
}, label: {
Text("Change button view 1")
.padding()
})
Button(action: {
dismiss.callAsFunction()
}, label: {
Text("Go to view 1")
})
}
.navigationBarBackButtonHidden(true)
}
}
struct ColorChange1: View {
#StateObject private var colorModel = ColorModel()
var body: some View {
NavigationView {
VStack {
Circle()
.fill(colorModel.isOnFirstView ? .green : .red)
.frame(width: 100)
Button(action: {
colorModel.didTapChangeColor(atFirstView: true)
}, label: {
Text("Change button view 2")
.padding()
})
NavigationLink(destination: {
ColorChange2(colorModel: colorModel)
}, label: {
Text("Go to view 2")
})
}
}
}
}
struct ColorChange_Previews: PreviewProvider {
static var previews: some View {
ColorChange1()
}
}

Multiple Bottom sheets - the content doesn't load SwiftUI

I have made a view with two possible bottom sheets. The action works, and Bottom Sheets do open. Crazy thing is they open without the view inside. I have to close the one I opened and open the other one. When I do and than come back to the first one I will see the content. The code builds without warnings:
LogInView - where the logic is:
import SwiftUI
struct LogInView: View {
#EnvironmentObject var userInfo: UserInfo
enum Action{
case resetPW, signUp
}
#State private var showSheet = false
#State private var action:Action?
var body: some View {
LoginEmailView(showSheet: $showSheet, action: $action)
.sheet(isPresented: $showSheet){
if self.action == .resetPW{
ModalResetPWView()
}else if self.action == .signUp{
ModalSignUpView()
}
}
}
}
The view from which actions come:
import SwiftUI
struct LoginEmailView: View {
#EnvironmentObject var userInfo: UserInfo
#StateObject var user:LogInViewModel = LogInViewModel()
// ----- > THERE IS BINDING
#Binding var showSheet: Bool
#Binding var action:LogInView.Action?
// ----- >
var body: some View {
VStack{
Spacer()
Image("logo")
HStack{
Text("Adres email:")
.padding(.horizontal, 10)
.font(.title)
.foregroundColor(.black)
Spacer()
}
TextField("Enter e-mail adress", text: self.$user.email)
.textFieldStyle(RoundedBorderTextFieldStyle())
.font(.title)
.padding(.horizontal, 10)
.keyboardType(.emailAddress)
HStack{
Text("Password:")
.padding(.horizontal, 10)
.font(.title)
.foregroundColor(.black)
Spacer()
}
SecureField("Enter password", text: self.$user.password)
.textFieldStyle(RoundedBorderTextFieldStyle())
.font(.title)
.padding(.horizontal,10)
HStack{
Spacer()
// ----- > First Bottom sheet
Button(action: {
self.action = .resetPW
self.showSheet = true
}) {
Text("Forgot Password")
}
.padding(.top, 5)
.padding(.trailing, 10)
// ----- >
}
Button(action: {
self.userInfo.isAuthenticated = .signedIn
}) {
Text("Log in")
}
.font(.title)
.padding(5)
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(10)
.padding(.top, 10)
.opacity(user.isLogInComplete ? 1 : 0.7)
.disabled(!user.isLogInComplete)
// ----- > Second bottom sheet
Button(action: {
self.action = .signUp
self.showSheet = true
}) {
Text("Sign Up")
}
// ----- >
.padding(.top, 35)
Spacer()
}
}
}
The .sheet modifier will create the sheet view as soon as LogInView() is initialized. In your 'if.. else if..' statement, there is no logic to catch 'else' situations (situations where action == nil). Therefore, since action == nil on init(), the first .sheet that will present will fail your 'if..else if' and an EmptyView will present.
But don't worry! This is a common issue and can be easily solved. Here are 2 easy ways to implement methods to fix this (I prefer the 2nd method bc it's cleaner):
METHOD 1: Present a single view & change that view's content instead of switching between which view to present.
Instead of doing the 'if.. else if..' statement within the .sheet modifier, present a static view (I've called it SecondaryView ) that has a #Binding variable connected to your action. This way, when LogInView() appears, we can ensure that it will definitely render this view and then we can simply modify this view's content by changing the #Binding action.
import SwiftUI
struct LogInView: View {
enum Action{
case resetPW, signUp
}
#State private var showSheet = false
#State private var action: Action?
var body: some View {
LoginEmailView(showSheet: $showSheet, action: $action)
.sheet(isPresented: $showSheet) {
SecondaryView(action: $action)
}
}
}
struct LoginEmailView: View {
#Binding var showSheet: Bool
#Binding var action: LogInView.Action?
var body: some View {
VStack(spacing: 40 ){
Text("Forgot Password")
.onTapGesture {
action = .resetPW
showSheet.toggle()
}
Text("Sign Up")
.onTapGesture {
action = .signUp
showSheet.toggle()
}
}
}
}
struct SecondaryView: View {
#Binding var action: LogInView.Action?
var body: some View {
if action == .signUp {
Text("SIGN UP VIEW HERE")
} else {
Text("FORGOT PASSWORD VIEW HERE")
}
}
}
METHOD 2: Make each Button it's own View, so that it can have it's own .sheet modifier.
In SwiftUI, we are limited to 1 .sheet() modifier per View. However, we can always add Views within Views and each subview is then allowed it's own .sheet() modifier as well. So the easy solution is to make each of your buttons their own view. I prefer this method because we no longer need to pass around the #State/#Binding variables between views.
struct LogInView: View {
var body: some View {
LoginEmailView()
}
}
struct LoginEmailView: View {
var body: some View {
VStack(spacing: 40 ){
ForgotPasswordButton()
SignUpButton()
}
}
}
struct ForgotPasswordButton: View {
#State var showSheet: Bool = false
var body: some View {
Text("Forgot Password")
.onTapGesture {
showSheet.toggle()
}
.sheet(isPresented: $showSheet, content: {
Text("FORGOT PASSWORD VIEW HERE")
})
}
}
struct SignUpButton: View {
#State var showSheet: Bool = false
var body: some View {
Text("Sign Up")
.onTapGesture {
showSheet.toggle()
}
.sheet(isPresented: $showSheet, content: {
Text("SIGN UP VIEW HERE")
})
}
}

Updating #Published variable of an ObservableObject inside child view

I have a published variable isLoggedIn inside a ObservableObject class as follows:
import Combine
class UserAuth: ObservableObject{
#Published var isLoggedIn: Bool = false
}
I want to update this variable to true in a particular view (LoginView). This variable determines what view I show the user depending if the user has logged in or not:
struct ContentView: View {
#ObservedObject var userAuth = UserAuth()
var body: some View {
Group{
if(userAuth.isLoggedIn){
MainView()
}else{
AccountView()
}
}
}
}
Because userAuth.isLoggedIn is false (I haven't logged in) AccountView is displayed.
AccountView:
struct AccountView: View {
#State private var toggleSheet = false
var body: some View {
VStack {
Spacer()
Button(action: {
self.toggleSheet.toggle()
}){
Text("Toggle Modal")
.padding()
.foregroundColor(Color.white)
.background(Color.blue)
.cornerRadius(10)
}
.sheet(isPresented: self.$toggleSheet){
LoginView()
}
Spacer()
}
}
}
Whenever the user presses the button the LoginView Modal is shown:
struct LoginView: View {
var body: some View {
VStack{
Button(action: {
return self.login()
}){
Text("Log in")
.padding()
.foregroundColor(Color.white)
.background(Color.green)
.cornerRadius(10)
}
}
}
func login(){
// update UserAuth().isLoggedIn to TRUE
}
}
In the LoginView there is a button, the logic I want is for the user to press the button, login() gets called and inside that function userAuth.isLoggedIn is set to true. What would be the best way to implement this ?
I've tried to directly change the value and I get an error along the lines of:
Publishing changes from background threads is not allowed; make sure to publish values from the main thread (via operators like receive
Try embedding your code in DispatchQueue.main.async like this:
func login(){
DispatchQueue.main.async {
//update UserAuth().isLoggedIn to TRUE
}
}
One possibility would be to insert the UserAuth object from the ContentView into the subviews as an EnvironmentObject.
struct ContentView: View {
#ObservedObject var userAuth = UserAuth()
var body: some View {
Group {
if userAuth.isLoggedIn {
MainView()
} else {
AccountView()
.environmentObject(userAuth)
}
}
}
}
Now userAuth is accessible in AccountView and all its subviews (e.g. LoginView):
struct LoginView: View {
// Access to the environment object
#EnvironmentObject private var userAuth: UserAuth
var body: some View {
VStack {
Button(action: {
return self.login()
}) {
Text("Log in")
.padding()
.foregroundColor(Color.white)
.background(Color.green)
.cornerRadius(10)
}
}
}
func login() {
// Update the value on the main thread
DispatchQueue.main.async {
self.userAuth.isLoggedIn = true
}
}
}
It may be necessary to insert the EnvironmentObject into the LoginView manually. You can do this by accessing it in the AccountView and inserting it in the LoginView:
struct AccountView: View {
#State private var toggleSheet = false
// Access the value, that was inserted in `ContentView`
#EnvironmentObject private var userAuth: UserAuth
var body: some View {
VStack {
Spacer()
Button(action: {
self.toggleSheet.toggle()
}){
Text("Toggle Modal")
.padding()
.foregroundColor(Color.white)
.background(Color.blue)
.cornerRadius(10)
}
.sheet(isPresented: self.$toggleSheet){
LoginView()
// Insert UserAuth object again
.environmentObject(self.userAuth)
}
Spacer()
}
}
}
Further Reading
WWDC 2019 Video | Hacking with Swift Example