Skip to content

Delete and add contents of List with SwiftUI

   

It is a way to add and delete contents in List in SwiftUI. It seems bad to pass a delete function in closure. Please let me know if there is a better way.

AddDeleteList

import SwiftUI
struct ContentView: View {
@State var fruits: [Fruit] = [Fruit(name: "Apple"), Fruit(name: "Banana"), Fruit(name: "Grape")]
var body: some View {
ZStack {
List(fruits) { fruit in
Row(fruit: fruit) { id in
self.removeFruit(id: id)
}
}
VStack {
Spacer()
Button(action: {
self.fruits.append(Fruit(name: "New Fruit"))
}) {
Text("Add Fruit")
.font(Font.system(size: 20))
.padding()
.border(Color.gray)
}
}
}
}
func removeFruit(id: UUID) {
if let index = fruits.firstIndex(where: { $0.id == id }) {
fruits.remove(at: index)
}
}
}
struct Fruit: Identifiable {
let id = UUID()
let name: String
}
struct Row: View {
let fruit: Fruit
let closure: (_ id: UUID) -> Void
var body: some View {
HStack {
Text(fruit.name)
.padding()
Spacer()
Button(action: {
self.closure(self.fruit.id)
}) {
Text("Delete")
.font(Font.system(size: 20))
.padding()
.border(Color.gray)
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}

  1. Create a sequential numbered array in Swift
  2. Hide keyboard with buttons in SwiftUI
  3. Detect keyboard height and appearance with SwiftUI
  4. Input a multi-line string with SwiftUI
  5. Show picker from bottom with SwiftUI
  6. Using UIImagePickerController with SwiftUI
  7. Do not change the color of the Image in the Button with SwiftUI