SebaSbs
SebaSbs

Reputation: 353

How can I create a popup menu in iOS?

How can I create a popup menu like the one present in WhatsApp?

Screenshot of the popup menu

Sorry for the dumb question, but I don't even know what to search. I'm pretty sure it's not a UIPickerView.

Upvotes: 10

Views: 14957

Answers (2)

user3151675
user3151675

Reputation: 58029

This is an action sheet. Here's the documentation about it in the iOS Human Interface Guidelines.

You can make one like this:

SwiftUI (iOS 15 and above)

Use confirmationDialog(). Here is the official documentation for it and here are some real-world examples, which are partially the source of the example code.

@State private var shouldShowActionSheet = false

<custom view>
.confirmationDialog("", isPresented: $shouldShowActionSheet) {
    Button("Option 1") {
        <handler>
    }

    Button("Option 2") {
        <handler>
    }

    Button("Cancel", role: .cancel) { }
}

SwiftUI (iOS 13 and 14)

@State private var shouldShowActionSheet = false

[...]

<custom view>
.actionSheet(isPresented: $shouldShowActionSheet) {
    ActionSheet(
        title: Text(""),
        buttons: [
            .default(Text("Option 1")) {
                <handler>
            },
            .default(Text("Option 2")) {
                <handler>
            },
            .cancel()
        ]
    )
}

UIKit

let alert = UIAlertController(
    title: nil,
    message: nil, 
    preferredStyle: .actionSheet
)

alert.addAction(
    .init(title: "Action 1", style: .default) { _ in
        <handler>
    }
)

alert.addAction(
    .init(title: "Action 2", style: .default) { _ in
        <handler>
    }
)

alert.addAction(.init(title: "Cancel", style: .cancel))

present(alert, animated: true)

Upvotes: 19

snjmhj
snjmhj

Reputation: 1081

Its UIAlertController with preferredStyle - UIAlertControllerStyle.actionSheet https://developer.apple.com/documentation/uikit/uialertcontroller

Upvotes: 1

Related Questions