如何在iOS中创建弹出菜单?

9
如何创建类似 WhatsApp 中的弹出菜单?
抱歉问一个傻问题,但我甚至不知道该搜索什么。我很确定它不是 UIPickerView。

3
在发布这样的问题之前,您应该查阅iOS人机界面指南。请点击链接:https://developer.apple.com/ios/human-interface-guidelines/ - rmaddy
3
基本问题在于命名使得很难找到解决方案 UIAlertController,但这个问题实际上是问题和答案之间的连接器。好问题。 - Jan Bergström
2个回答

18
这是一个操作表在iOS人机界面指南中有关它的文档。
你可以像这样制作一个:

SwiftUI(iOS 15及以上)

使用confirmationDialog()这里是官方文档这里有一些现实世界的例子,部分是示例代码的来源。
@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和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)

1
在这个优秀的答案上,只需要注意,在带有弹出窗口的所有情况下,您不可避免地需要添加一个.cancel操作。只需添加一个样式为.cancel的操作。重要的是,这也解决了当用户单击“屏幕上的任何其他位置”以关闭弹出窗口时的问题。 - Fattie
我们很棒,Tamás! - Fattie

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接