Created
March 6, 2020 06:25
SwiftUIでListの要素を削除した入り増やしたりする
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() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment