32

I've gotten an ActionSheet to present just fine on an iPhone device. But it crashes for iPad. Says it needs the location for the popover. Has anyone had luck with this code? I'm using iOS 13 beta 3 and Xcode 11 beta 3. (This uses a version of presenting the ActionSheet not available in beta 2)

import SwiftUI

struct ContentView : View {
    @State var showSheet = false

    var body: some View {
        VStack {
            Button(action: {
                self.showSheet.toggle()
            }) {
                Text("Show")
            }
            .presentation($showSheet) { () -> ActionSheet in
                ActionSheet(title: Text("Hello"))

            }
        }
    }
}

#if DEBUG
struct ContentView_Previews : PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
#endif
3
  • 2
    I can duplicate this, along with the deprecated way. Worse, while it works on an iPhone (at least in the simulator, I don't have an iPhone yet running iOS 13) it yields conflicting constraints! My only question, seeing as I haven't used an ActionSheet before in SwiftUI, did it ever behave better in earlier betas? My best guess is to chalk it up as a beta bug and report it to Apple.
    – user7014451
    Commented Jul 6, 2019 at 12:03
  • If someone is wondering why their basic sheet view isn't presenting on an iPad (but was fine on a phone, nested in a NavigationView), your view is there - to view it you need to swipe from the left edge to get it to show. To fix add .navigationViewStyle(StackNavigationViewStyle()) to your modal.
    – DogCoffee
    Commented Nov 22, 2019 at 4:29
  • What I'm finding weird is that some of my action sheets present just fine on an iPad/Catalyst whereas others give this error. Anybody else had that? (without setting the popover sourceRect in either case)
    – andygeers
    Commented Mar 20, 2020 at 23:09

6 Answers 6

20

Sadly, this bug has not been fixed for the final release of iOS 13. It was mentioned on the developer forums, and I've filed a feedback for it (FB7397761), but for the time being one needs to work around it by using some other UI when UIDevice.current.userInterfaceIdiom == .pad.

For the record, the (unhelpful) exception message is:

2019-10-21 11:26:58.205533-0400 LOOksTape[34365:1769883] *** Terminating app due to uncaught exception 'NSGenericException', reason: 'Your application has presented a UIAlertController (<UIAlertController: 0x7f826e094a00>) of style UIAlertControllerStyleActionSheet from _TtGC7SwiftUI19UIHostingController… 
The modalPresentationStyle of a UIAlertController with this style is UIModalPresentationPopover. 
You must provide location information for this popover through the alert controller's popoverPresentationController. 
You must provide either a sourceView and sourceRect or a barButtonItem.  
If this information is not known when you present the alert controller, you may provide it in the UIPopoverPresentationControllerDelegate method -prepareForPopoverPresentation.'

As a workaround, this popSheet function will display a popover on the iPad and an ActionSheet everywhere else:

public extension View {
    /// Creates an `ActionSheet` on an iPhone or the equivalent `popover` on an iPad, in order to work around `.actionSheet` crashing on iPad (`FB7397761`).
    ///
    /// - Parameters:
    ///     - isPresented: A `Binding` to whether the action sheet should be shown.
    ///     - content: A closure returning the `PopSheet` to present.
    func popSheet(isPresented: Binding<Bool>, arrowEdge: Edge = .bottom, content: @escaping () -> PopSheet) -> some View {
        Group {
            if UIDevice.current.userInterfaceIdiom == .pad {
                popover(isPresented: isPresented, attachmentAnchor: .rect(.bounds), arrowEdge: arrowEdge, content: { content().popover(isPresented: isPresented) })
            } else {
                actionSheet(isPresented: isPresented, content: { content().actionSheet() })
            }
        }
    }
}

/// A `Popover` on iPad and an `ActionSheet` on iPhone.
public struct PopSheet {
    let title: Text
    let message: Text?
    let buttons: [PopSheet.Button]

    /// Creates an action sheet with the provided buttons.
    public init(title: Text, message: Text? = nil, buttons: [PopSheet.Button] = [.cancel()]) {
        self.title = title
        self.message = message
        self.buttons = buttons
    }

    /// Creates an `ActionSheet` for use on an iPhone device
    func actionSheet() -> ActionSheet {
        ActionSheet(title: title, message: message, buttons: buttons.map({ popButton in
            // convert from PopSheet.Button to ActionSheet.Button (i.e., Alert.Button)
            switch popButton.kind {
            case .default: return .default(popButton.label, action: popButton.action)
            case .cancel: return .cancel(popButton.label, action: popButton.action)
            case .destructive: return .destructive(popButton.label, action: popButton.action)
            }
        }))
    }

    /// Creates a `.popover` for use on an iPad device
    func popover(isPresented: Binding<Bool>) -> some View {
        VStack {
            ForEach(Array(buttons.enumerated()), id: \.offset) { (offset, button) in
                Group {
                    SwiftUI.Button(action: {
                        // hide the popover whenever an action is performed
                        isPresented.wrappedValue = false
                        // another bug: if the action shows a sheet or popover, it will fail unless this one has already been dismissed
                        DispatchQueue.main.async {
                            button.action?()
                        }
                    }, label: {
                        button.label.font(.title)
                    })
                    Divider()
                }
            }
        }
    }

    /// A button representing an operation of an action sheet or popover presentation.
    ///
    /// Basically duplicates `ActionSheet.Button` (i.e., `Alert.Button`).
    public struct Button {
        let kind: Kind
        let label: Text
        let action: (() -> Void)?
        enum Kind { case `default`, cancel, destructive }

        /// Creates a `Button` with the default style.
        public static func `default`(_ label: Text, action: (() -> Void)? = {}) -> Self {
            Self(kind: .default, label: label, action: action)
        }

        /// Creates a `Button` that indicates cancellation of some operation.
        public static func cancel(_ label: Text, action: (() -> Void)? = {}) -> Self {
            Self(kind: .cancel, label: label, action: action)
        }

        /// Creates an `Alert.Button` that indicates cancellation of some operation.
        public static func cancel(_ action: (() -> Void)? = {}) -> Self {
            Self(kind: .cancel, label: Text("Cancel"), action: action)
        }

        /// Creates an `Alert.Button` with a style indicating destruction of some data.
        public static func destructive(_ label: Text, action: (() -> Void)? = {}) -> Self {
            Self(kind: .destructive, label: label, action: action)
        }
    }
}

4
  • Thank @marcprux!!! However, the code needs some modifications to run. Here what I did medium.com/@liemvo/…
    – Liem Vo
    Commented Nov 29, 2019 at 9:29
  • 1
    I’m my case if crashes on: DispatchQueue.main.async { button.action?() } my fix is: DispatchQueue.main.asyncAfter(deadline: .now() + 0.1, execute: { button.action?() }) Commented Feb 4, 2020 at 17:49
  • Thanks Roman! Since I can't use the official fix because our devices are not yet at 13.4, I noticed that my iPad Actions were not dismissing without the delayed execution that Roman suggested! That would have taken me hours to debug. Thanks!
    – Dave Levy
    Commented Feb 27, 2020 at 19:04
  • I had a layout issue rather than a crash (ActionSheet appearing off screen on iPad), this answer put me in the right direction. However, I needed to specify some dimensions manually and change the attachmentAnchor amongst other things. Here's a gist.
    – skl_
    Commented Jun 19, 2020 at 1:20
10

Finally, as tested in iOS 13.4 this has been resolved, at least in the beta. The conflicting constraints warning persists, but the crash is gone. This is now the appropriate way to present an action sheet.

import SwiftUI

struct ContentView : View {
    @State var showSheet = false

    var body: some View {
        VStack {
            Button(action: {
                self.showSheet.toggle()
            }) {
                Text("Show")
            }
            .actionSheet(isPresented: $showSheet, content: { ActionSheet(title: Text("Hello"))
            })
        }
    }
}

struct ContentView_Previews : PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
2
  • 2
    Just tested this on the iPad simulator running iOS 13.4 and nothing shows, just the '[LayoutConstraints] Unable to simultaneously satisfy constraints' error. Of course the action sheet shows fine on an iPhone (iOS 13.4)
    – cgiacomi
    Commented Apr 12, 2020 at 9:36
  • Yup. You can't attach it to the button unfortunately but only to the root view of your body. Then it'll show but it'll not be displayed correctly.
    – Dimillian
    Commented Apr 24, 2020 at 10:37
1

Try this component, it will present an actionSheet on iPhone and a Popover on iPad and Mac. https://github.com/AndreaMiotto/ActionOver

0

Use the newer (iOS 15) alert modifier to present an alert in the center. That works well for iPad, unlike the ActionSheet that they never seem to fix.

.alert("Hello", isPresented: $showSheet) {
    // Add your buttons here
}
-3

Here's my workaround for the bug - it maintains the "actionsheet" functionality for iPhone devices but simply creates an "alert" style controller for iPad

It's simple enough for my case and may help others

    var preferredStyle: UIAlertController.Style
    if UIDevice.current.userInterfaceIdiom == .pad {
        preferredStyle = .alert
    }
    else{
        preferredStyle = .actionSheet
    }
    let cellMenu = UIAlertController(title: nil, message: "Bought Item?", preferredStyle: preferredStyle)

    //Create actions
    //Add Actions to menu

    self.present(cellMenu, animated: true, completion: nil)
2
  • Thanks. Just what I was looking for. Simple solution. Commented Dec 26, 2019 at 22:27
  • 3
    The question asks about ActionSheets in SwiftUI, not UIKit UIAlertController which have a different set of challenges.
    – Eugene
    Commented Jan 14, 2020 at 23:53
-5

It is a known bug of beta. Just wait for a fix.

1
  • 7
    I wish I could say it is known. I submitted this bug in Feedback a long time ago with no response, and I don't see it listed as a known issue in Apple's release notes. Commented Aug 30, 2019 at 23:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.