SwiftUI中的List出现问题。从列表中删除任何项目都会崩溃,错误为Fatal error: Index out of range
。使用onDelete
方法不起作用,在我的自定义函数中也不起作用。我在做什么错了?
它是 macOS 应用,不是iOS。我在macOS 10.15.1上并使用Xcode 11.2.1。
这是我的代码:
import SwiftUI
struct TodoItem: Identifiable {
var id = UUID()
var name: String
var isCompleted = false
}
struct TodoRow: View {
@Binding var todo: TodoItem
@State var buttonHover: Bool = false
var index: Int
var removeTodo: (_ index: Int) -> Void
func toggleTodo() {
self.$todo.isCompleted.wrappedValue.toggle()
}
var body: some View {
VStack(alignment: .leading) {
HStack {
Button(action: toggleTodo) {
Image(nsImage: NSImage(named: NSImage.Name(NSImage.menuOnStateTemplateName))!)
.resizable()
.frame(width: 8, height: 8)
.padding(3)
.opacity(todo.isCompleted ? 1 : buttonHover ? 0.5 : 0)
}.buttonStyle(PlainButtonStyle())
.background(Capsule().stroke(Color.primary, lineWidth: 1))
.onHover(perform: { val in self.buttonHover = val })
Text("\(todo.name)").strikethrough(todo.isCompleted, color: Color.primary)
}.opacity(todo.isCompleted ? 0.35 : 1)
Divider().fixedSize(horizontal: false, vertical: true).frame(height: 1)
}.contextMenu {
Button(action: {
self.removeTodo(self.index)
}) {
Text("Remove")
}
}
}
}
struct TodoList: View {
var listName: String
@State var newTodo: String = ""
@State var todos: [TodoItem] = []
@State var showCompleted = false
func addTodo() {
let trimmedTodo = newTodo.trimmingCharacters(in: .whitespacesAndNewlines)
if !trimmedTodo.isEmpty {
todos.insert(TodoItem(name: trimmedTodo), at: 0)
newTodo = ""
}
}
func removeTodo(index: Int) -> Void {
// remove is crashing the app :(
self.todos.remove(at: index)
}
var body: some View {
return VStack(alignment: .leading) {
Text("\(listName)").font(.system(size: 20))
HStack {
TextField("New todo...", text: $newTodo)
NativeButton("Add", keyEquivalent: .return) {
self.addTodo()
}
}
List {
ForEach(todos.indices.filter { self.showCompleted || !self.todos[$0].isCompleted }, id: \.self) { index in
TodoRow(todo: self.$todos[index], index: index, removeTodo: self.removeTodo)
}.onDelete{offsets in
// remove is crashing the app :(
self.todos.remove(atOffsets: offsets)
}
}
Toggle(isOn: $showCompleted) {
Text("Show completed")
}
}.padding().frame(minWidth: 400, maxWidth: .infinity, minHeight: 200, maxHeight: .infinity)
}
}
struct TodoList_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
感谢您的帮助,也为混乱的代码感到抱歉,我还是Swift和SwiftUI的新手。
答案 0 :(得分:1)
您好,我注意到您正在过滤索引,并检查了delete的偏移量,发现有时偏移量范围与实际索引不同,我尝试更改一些内容:
List {
ForEach(todos.filter { self.showCompleted || !$0.isCompleted }, id: \.self) { item in
TodoRow(todo: item)
}.onDelete{offsets in
self.todos.remove(atOffsets: offsets)
}
}
并且这种方式需要使TodoItem
符合'Hashable'-> struct TodoItem: Identifiable, Hashable
因此,如果它不能解决您的问题,请尝试将我打回
答案 1 :(得分:0)
所以 fakiho 的答案(谢谢!)不是完整的解决方案,但是它帮助我找到了解决方案。我认为问题出在@Binding var todo: TodoItem
中的TodoRow
。我最终通过了我需要的所有属性,而不是整个TodoItem
,并且可以正常工作。
如果有人遇到同样的问题,这里是完整的工作代码:
struct TodoRow: View {
@State var buttonHover: Bool = false
var name: String
var isCompleted: Bool
var toggleItem: () -> Void
var removeItem: () -> Void
var body: some View {
VStack(alignment: .leading) {
HStack {
Button(action: toggleItem) {
Image(nsImage: NSImage(named: NSImage.Name(NSImage.menuOnStateTemplateName))!)
.resizable()
.frame(width: 8, height: 8)
.padding(3)
.opacity(isCompleted ? 1 : buttonHover ? 0.5 : 0)
}.buttonStyle(PlainButtonStyle())
.background(Capsule().stroke(Color.primary, lineWidth: 1))
.onHover(perform: { val in self.buttonHover = val })
Text("\(name)").strikethrough(isCompleted, color: Color.primary)
}.opacity(isCompleted ? 0.35 : 1)
Divider().fixedSize(horizontal: false, vertical: true).frame(height: 1)
}.contextMenu {
Button(action: removeItem) {
Text("Delete")
}
}
}
}
struct TodoList: View {
var listName: String
@State var newTodo: String = ""
@State var todos: [TodoItem] = []
@State var showCompleted = false
func addTodo() {
let trimmedTodo = newTodo.trimmingCharacters(in: .whitespacesAndNewlines)
if !trimmedTodo.isEmpty {
todos.insert(TodoItem(name: trimmedTodo), at: 0)
newTodo = ""
}
}
var body: some View {
return VStack(alignment: .leading) {
Text("\(listName)").font(.headline)
HStack {
TextField("New todo...", text: $newTodo)
NativeButton("Add", keyEquivalent: .return) {
self.addTodo()
}
}
List {
ForEach(todos.indices.filter { self.showCompleted || !todos[$0].isCompleted }, id: \.self) { index in
TodoRow(
name: self.todos[index].name,
isCompleted: self.todos[index].isCompleted,
toggleItem: {
self.$todos[index].isCompleted.wrappedValue.toggle()
},
removeItem: {
self.todos.remove(at: index)
}
)
}.onDelete { offsets in
self.todos.remove(atOffsets: offsets)
}
}
Toggle(isOn: $showCompleted) {
Text("Show completed")
}
}.padding().frame(minWidth: 400, maxWidth: .infinity, minHeight: 200, maxHeight: .infinity)
}
}