List

Swift

配列と繰り返し処理

struct ContentView: View {
    var taskData = ["ジョギング", "水やり", "掃除", "読書"]

    var body: some View {
        NavigationStack {
            List(0..<taskData.count, id: \.self) { index in
                Button {
                } label: {
                    HStack {
                        Image(systemName: "circle")
                        Text(taskData[index])
                    }
                }
                .foregroundColor(.black)
            }
            .navigationTitle("ToDoリスト")
        }
    }
}

配列と繰り返し処理2

struct ContentView: View {
    @State var taskData = [(title: "ジョギング", completed: false),
                           (title: "水やり", completed: false),
                           (title: "掃除", completed: false),
                           (title: "読書", completed: false)]

    var body: some View {
        NavigationStack {
            List(0..<taskData.count, id: \.self) { index in
                Button {
                    taskData[index].completed.toggle()  ※1
                } label: {
                    HStack {
                        Image(systemName: taskData[index].completed == true ? "checkmark.circle.fill" : "circle")
                        Text(taskData[index].title)
                    }
                }
                .foregroundColor(.black)
            }
            .navigationTitle("ToDoリスト")
        }
    }
}

※1 … taskData[index].completed = !taskData[index].completed とも書けます

※2 … if taskData[index].completed == true {
Image(systemName: “checkmark.circle.fill”)
} else {
Image(systemName: “circle”)
} とも書けます

BACK