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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} | |
} |