swiftui - 是否可以在 SwiftUI 中创建具有 2 个以上按钮的警报?

标签 swiftui

我需要创建一个带有 3 个按钮的警报,但看起来 SwiftUI 现在只给了我们两个选项:一个按钮或两个按钮。我知道使用 UIKit,可以实现 3 个按钮,但我似乎无法在最新版本的 SwiftUI 中找到解决方法来执行此操作。下面是我只使用主要和次要按钮的代码。

Button(action: {
    self.showAlert = true
}){
    Text("press me")
}
.alert(isPresented: self.$showAlert){
     Alert(title: Text("select option"), message: Text("pls help"), primaryButton: Alert.Button.default(Text("yes"), action: {
         print("yes clicked")
         }), secondaryButton: Alert.Button.cancel(Text("no"), action: {
         print("no clicked")
     })
     )
}

最佳答案

.actionSheet、.sheet 和 .popover 是提供自定义警报的选项。考虑这个示例:

import SwiftUI

struct ContentView: View {
    @State private var showModal = false
    @State private var cnt = 0
    var body: some View {
        
        VStack {
            Text("Counter is \(cnt)")
            Button("Show alert") {
                self.showModal = true
            }
        }
        .sheet(isPresented: $showModal,
               onDismiss: {
                print(self.showModal)}) {
                    CustomAlert(message: "This is Modal view",
                              titlesAndActions: [("OK", {}),
                                                 ("Increase", { self.cnt += 1 }),
                                                 ("Cancel", nil)])
        }
    }
}

struct CustomAlert: View {
    @Environment(\.presentationMode) var presentation
    let message: String
    let titlesAndActions: [(title: String, action: (() -> Void)?)] // = [.default(Text("OK"))]
    
    var body: some View {
        VStack {
            Text(message)
            Divider().padding([.leading, .trailing], 40)
            HStack {
                ForEach(titlesAndActions.indices, id: \.self) { i in
                    Button(self.titlesAndActions[i].title) {
                        (self.titlesAndActions[i].action ?? {})()
                        self.presentation.wrappedValue.dismiss()
                    }
                    .padding()
                }
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

关于swiftui - 是否可以在 SwiftUI 中创建具有 2 个以上按钮的警报?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57839664/

相关文章:

ios - SwiftUI - 动画计数文本从 0 到 x

SwiftUI:结构 View 与@ViewBuilder

swift - 尝试从 WWDC session 重新创建基于 SwiftUI 的应用程序时出现问题

ios - 订阅对@Published 的更改

swift - 使用 AVFoundation 旋转 UIViewRepresentable View

ios - 如何声明正确的内容以将另一个 swiftui 文件导入到 contentview 文件中?

Swift - 如何从 View 之外的函数访问@Published var?

ios - 当模型在 @Published 属性内更新时,SwiftUI 触发函数

ZStack 中的 SwiftUI 图像未与屏幕底部对齐

ios - SwiftUI 图像作为自定义 "radio"按钮