SwiftUI:有条件的 onDelete
Posted
技术标签:
【中文标题】SwiftUI:有条件的 onDelete【英文标题】:SwiftUI: Conditional onDelete 【发布时间】:2020-10-05 17:26:40 【问题描述】:我正在尝试创建一个仅允许用户在进入编辑模式后删除的列表。我试图尝试在 onDelete 修饰符中使用三元运算,但无法弄清楚。有什么建议吗?
这是我的代码:
struct ContentView: View
@State private var stuff = ["First", "Second", "Third"]
@State private var check = false
var body: some View
Form
Button(action: check.toggle() , label: Text(check ? "Editing" : "Edit") )
ForEach(0..<stuff.count) items in
Section Text(stuff[items])
.onDelete(perform: self.deleteItem)
private func deleteItem(at indexSet: IndexSet)
self.stuff.remove(atOffsets: indexSet)
【问题讨论】:
【参考方案1】:我假设您正在寻找以下内容
var body: some View
Form
Button(action: check.toggle() , label: Text(check ? "Editing" : "Edit") )
ForEach(0..<stuff.count) items in
Section Text(stuff[items])
.onDelete(perform: self.deleteItem)
.deleteDisabled(!check) // << this one !!
【讨论】:
【参考方案2】:struct ContentView: View
@State private
var stuff = ["First", "Second", "Third"]
var body: some View
NavigationView
Form
ForEach(0..<stuff.count) item in
Section
Text(stuff[item])
.onDelete(
perform: delete)
.navigationBarItems(
trailing:
EditButton()
)
.navigationTitle("Test")
extension ContentView
private func delete(at indexSet: IndexSet)
stuff.remove(atOffsets: indexSet)
【讨论】:
以上是关于SwiftUI:有条件的 onDelete的主要内容,如果未能解决你的问题,请参考以下文章
使用 SwiftUI 和 Combine 根据授权状态有条件地显示视图?