首页 > 解决方案 > SwiftUI 从表单中删除项目导致崩溃

问题描述

我有一个数组Date(),在我的数组中Form我可以附加更多的日期。

 @State private var dates: [Date] = [Date()]

但是当我尝试删除一个日期时,它会导致崩溃。Index out of range. 当只剩下 1 个日期时,我禁用删除,所以这不是问题,因为此时您无法删除。

Section(header: Text("Notifications")) {
                ForEach(dates, id: \.self) { date in
                
                    let value = dates.firstIndex(of: date)!
                    
                    DatePicker("\(value + 1)", selection: $dates[value], displayedComponents: .hourAndMinute)
                    
                
                }.onDelete(perform: { (offsets) in
                    dates.remove(atOffsets: offsets)
                })
                .deleteDisabled(dates.count <= 1)
                   
                Button(action: {
                    
                    dates.append(Date())
                    
                }, label: {
                    Text("Add Notification")
                }).disabled(dates.count == 10)
            }

为什么会崩溃?

标签: swiftxcodeswiftui

解决方案


推荐阅读