我需要创建一个带有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")
})
)
}
答案 0 :(得分:0)
.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()
}
}