Post

Replies

Boosts

Views

Activity

Using Alerts in SwiftUI Frameworks
I am developing a SwiftUI UI framework that will be used in other projects where I cannot access the source code. The framework needs to show an alert. To do this, I use the .alert() view modifier inside the framework. This works fine, as long as the app that consumes the framework (where I don't control the source code) does not also add a .alert() to a parent view of the framework. If the app does this, the alert inside the framework stops working. This is obviously not ideal, because the user that consumes my framework should not have to worry about internal implementation details, and should be free to use an alert if they want. I have added some example code here that demonstrates my problem. This can be run in a Playground if you want to run it yourself. Note the comments showing which parts work and which parts don't work. import SwiftUI import PlaygroundSupport struct ContentView: View { 		var body: some View { 				ParentView() 		} } /* This code would be in the app, controlled by the consumer */ struct ParentView: View { 		@State var showAlert: Bool = false 		 		var body: some View { 				VStack { 						Button(action: { 								self.showAlert = true 						}) { 								Text("App button") 						} 						FrameworkView() 						 				}.alert(isPresented: $showAlert) { 						/* This alert works perfectly fine */ 						Alert(title: Text("This is inside the app")) 				} 				 		} } /* This code would be provided by the framework, controlled by me */ struct FrameworkView: View { 		@State var showAlert: Bool = false 		 		var body: some View { 				Button(action: { 						self.showAlert = true 				}) { 						Text("Framework Button") 				}.alert(isPresented: $showAlert) { 						/* This alert is never shown */ 						Alert(title: Text("This is inside the framework")) 				} 		} } PlaygroundPage.current.setLiveView(ContentView()) Under normal circumstances, the solution would be to place the .alert() in ParentView on Button instead of VStack, but because I cannot control what the consumer of my framework writes, this will not work in my case. Any suggestions on how I could: a) Avoid this problem, or b) Warn the user if they set an alert that conflicts with the framework's internal alert?
1
0
753
Jul ’20