SwiftUI from UIHostingController: showing ActionSheet gives warning about detached view controller
Asked Answered
A

0

7

I have created a SwiftUI view which I show in a MKMapView's annotation callout. I use UIHostingController to wrap the SwiftUI view, and use annotationView's detailCalloutAccessoryView property to set the view and display it. This works fine for the most part. I then added some buttons to the SwiftUI view, which when tapped need to display an alert or an action sheet.

Here is the code:

struct ContactProfileButton: View {
    @State var showActionSheet: Bool = false
    var body: some View {
        Button(action: {
            print("Profile button tapped!")
            self.showActionSheet.toggle()
        }){
            Image("profile").resizable()
        }.frame(width: 26.0, height: 26.0)
        .actionSheet(isPresented: $showActionSheet, content: {
            print("Profile button - show action sheet")
            return ActionSheet(title: Text("Profile title"),
                               message: Text("Profile message"),
                               buttons: [
                                .default(Text("Do something")),
                                .destructive(Text("Cancel"))
                               ])
        })
    }
}

When I tap the button, it works fine and displays an action sheet, but generates this warning in the console:

[Presentation] Presenting view controller <SwiftUI.PlatformAlertController: 0x7fac118b3a00> from detached view controller <TtGC7SwiftUI19UIHostingControllerVS_7AnyView: 0x7fac1fac8280> is discouraged.

What is the best way to resolve this warning? Should I be showing an Alert or ActionSheet from within the SwiftUI view, if it's hosted inside a UIHostingController? Or should I be doing this some other way?

Araarab answered 23/3, 2021 at 23:27 Comment(3)
Hi any luck if you are able to find the solution for same.Cott
I ended up creating a 'delegate' which is passed in from UIKit, and used to send messages from SwiftUI back to UIKit-land, and I show the alerts from there.Araarab
ok actually I got crashing but I trying some solution and it worked for meCott

© 2022 - 2024 — McMap. All rights reserved.