Swiftui:我如何在VSTACK中删除foreach行?
这是TaskModel
import Foundation
import SwiftUI
struct TaskModel: Identifiable, Codable {
var id = UUID().uuidString
var title : String
var selectedColor : Color
var remindedTime : Int
var taskDate : Date
}
这是我尝试过的ViewModel
import Foundation
import SwiftUI
class CalendarViewModel : ObservableObject {
@Published var tasks : [TaskModel] = []
@Published var currentMonth : Int = 0
func addTask(title : String, selectedColor : Color, reminderTime : Int, taskDate : Date) {
let newTask = TaskModel(title: title, selectedColor: selectedColor, remindedTime: reminderTime * 60, taskDate: taskDate)
tasks.append(newTask)
}
func deleteTask(task : TaskModel) {
if let index = tasks.firstIndex(where: {$0.id == task.id }) {
tasks.remove(at: index)
}
}
这是我尝试删除行的ForEach
VStack {
ForEach(vm.tasks.filter({vm.isSameDay(date1: $0.taskDate, date2: currentDate)})) { task in
TaskRowView(task: task)
.actionSheet(isPresented: $isShowActionSheet) {
ActionSheet(title: Text("Settings"), message: Text("Press the button that what you want to do
This is TaskModel
import Foundation
import SwiftUI
struct TaskModel: Identifiable, Codable {
var id = UUID().uuidString
var title : String
var selectedColor : Color
var remindedTime : Int
var taskDate : Date
}
This is ViewModel I tried
import Foundation
import SwiftUI
class CalendarViewModel : ObservableObject {
@Published var tasks : [TaskModel] = []
@Published var currentMonth : Int = 0
func addTask(title : String, selectedColor : Color, reminderTime : Int, taskDate : Date) {
let newTask = TaskModel(title: title, selectedColor: selectedColor, remindedTime: reminderTime * 60, taskDate: taskDate)
tasks.append(newTask)
}
func deleteTask(task : TaskModel) {
if let index = tasks.firstIndex(where: {$0.id == task.id }) {
tasks.remove(at: index)
}
}
This is the ForEach I tried to delete row
VStack {
ForEach(vm.tasks.filter({vm.isSameDay(date1: $0.taskDate, date2: currentDate)})) { task in
TaskRowView(task: task)
.actionSheet(isPresented: $isShowActionSheet) {
ActionSheet(title: Text("Settings"), message: Text("Press the button that what you want to do ????"), buttons: [
.cancel(), .destructive(Text("Delete"), action: {
vm.deleteTask(task: task)
}), .default(Text("Edit"), action: {
})
])
}
}
.onLongPressGesture {
isShowActionSheet.toggle()
}
}
And this is the picture of my app View.
The weird thing is when I tried to delete second row of the List, The first row is deleted and second is left.
But, I can't find my miss point.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
实现此目的的最简单方法是使用可选的选择变量和
.actionSheet()
的自定义绑定。请参阅下面的代码。我评论了重要的部分。为了演示目的,我还将您的代码更改为最小可重现示例 (MRE)。The simplest way to implement this is with an optional selection variable and a custom binding for the
.actionSheet()
. Please see the code below. I commented the important parts. I also changed your code to a Minimal Reproducible Example (MRE) for demonstration purposes.