Why do you have so much whitespace in your code? To make it more readable, cut down on the excessive use of the space character.
You don't need to put Group {} around your code. You should use Group {} when you want to apply the same modifiers to the items within. For example, these are equivalent:
Group {
Text("1")
Text("2")
}
.foregroundStyle(Color.green)
// ... and ...
Text("1")
.foregroundStyle(Color.green)
Text("2")
.foregroundStyle(Color.green)
This works for me:
import SwiftUI
struct ContentView: View {
@State var text: Array<String> = []
@State var showSheet = false
@State var textItemTemp = ""
var body: some View {
NavigationView {
if text.count <= 1 {
Text("no items")
} else {
List {
ForEach(0...text.count - 1, id: \.self) {i in. // -- NOTE: This is 0 to (array length - 1), i.e. if array length is 10, it's 0...9 not 1...9
Text(text[i])
.contextMenu {
Button(action: {
text.remove(at: i)
}, label: {
Label("Delete", systemImage: "delete.left")
})
}
}
}
}
}
.navigationTitle("Idea Book")
.toolbar {
Button(action: {
showSheet.toggle()
textItemTemp = ""
}, label: {
Image(systemName: "plus")
})
}
.onChange(of: text) {
save()
load()
}
.onAppear() {
save()
load()
}
.refreshable {
save()
load()
}
.sheet(isPresented: $showSheet) {
NavigationView {
List {
TextField("Item", text: $textItemTemp)
}
.navigationTitle("Add an Idea")
.toolbar {
Button("add") {
text.append(textItemTemp)
showSheet.toggle()
}
}
}
}
}
func save() {
let temp = text.joined(separator: "/[split]/")
UserDefaults.standard.set(temp, forKey: "text")
}
func load() {
let temp = UserDefaults.standard.string(forKey: "text") ?? ""
let tempArray = temp.components(separatedBy:"/[split]/")
text = tempArray
}
}
#Preview {
ContentView()
}