我想在按钮点击等事件中显示 ActionSheet(或任何其他模式,但警报)。
我找到了使用状态变量的方法。以这种方式显示它对我来说似乎有点奇怪,因为当 ActionSheet 手动关闭时我必须重置变量。
有更好的方法吗?
为什么有一个单独的方法来呈现警报,允许您将其可见性绑定(bind)到状态变量?我的方法有什么不同?
struct Sketch : View {
@State var showActionSheet = false
var body: some View {
ZStack {
Button(action: { showActionSheet = true }) { Text("Show") }
}
.presentation(showActionSheet ?
ActionSheet(
title: Text("Action"),
buttons: [
ActionSheet.Button.cancel() {
self. showActionSheet = false
}
])
: nil)
}
}
最佳答案
为了加强对状态变量方法的偏好,Apple 已采用警报和操作表 API。为了其他发现此问题的人的利益,这里是基于 Xcode 11 beta 7、iOS 13 的所有 3 种类型的更新示例。
@State var showAlert = false
@State var showActionSheet = false
@State var showAddModal = false
var body: some View {
VStack {
// ALERT
Button(action: { self.showAlert = true }) {
Text("Show Alert")
}
.alert(isPresented: $showAlert) {
// Alert(...)
// showAlert set to false through the binding
}
// ACTION SHEET
Button(action: { self.showActionSheet = true }) {
Text("Show Action Sheet")
}
.actionSheet(isPresented: $showActionSheet) {
// ActionSheet(...)
// showActionSheet set to false through the binding
}
// FULL-SCREEN VIEW
Button(action: { self.showAddModal = true }) {
Text("Show Modal")
}
.sheet(isPresented: $showAddModal, onDismiss: {} ) {
// INSERT a call to the new view, and in it set showAddModal = false to close
// e.g. AddItem(isPresented: self.$showAddModal)
}
}
关于swift - 使用 SwiftUI 呈现 ActionSheet 的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56479159/