本节课演示如何配合NavigationView,删除List列表里的元素。
示例代码:
struct ContentView : View { @State var languages = ["Objective-C", "Swift", "Flutter"] var body: some View { NavigationView { List { ForEach(languages,id: \.self) { language in Text(language) } .onDelete(perform: delete) //添加对onDelete方法的响应,当列表里的记录被删除时,执行delete方法,该方法将在下面的代码中实现 } .navigationBarItems(trailing: EditButton()) } } func delete(at offsets: IndexSet) { if let first = offsets.first { //获得索引集合里的第一个元素,然后从数组里删除对应索引的元素 languages.remove(at: first) } } }