//
// ToDoViewModel.swift
// MyListApp
//
// Created by TAKESHI SHIMADA on 2024/07/02.
//
import Foundation
class ToDoViewModel: ObservableObject {
@Published var toDoItems = [
ToDoItem(title: "Buy groceries", isCompleted: false),
ToDoItem(title: "Walk the dog", isCompleted: true),
ToDoItem(title: "Read a book", isCompleted: false)
]
}
View
//
// ContentView.swift
// MyListApp
//
// Created by TAKESHI SHIMADA on 2024/07/02.
//
import SwiftUI
struct ContentView: View {
@StateObject private var viewModel = ToDoViewModel()
var body: some View {
NavigationView {
List(viewModel.toDoItems) { item in
HStack {
Text(item.title)
Spacer()
if item.isCompleted {
Image(systemName: "checkmark.circle.fill")
.foregroundColor(.green)
} else {
Image(systemName: "circle")
.foregroundColor(.gray)
}
}
}
.navigationTitle("To-Do List")
}
}
}
#Preview {
ContentView()
}
Model
//
// ToDoItem.swift
// MyListApp
//
// Created by TAKESHI SHIMADA on 2024/07/02.
//
import Foundation
struct ToDoItem: Identifiable {
let id = UUID()
let title: String
let isCompleted: Bool
}
App Entry
//
// MyListAppApp.swift
// MyListApp
//
// Created by TAKESHI SHIMADA on 2024/07/02.
//
import SwiftUI
@main
struct MyListAppApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
MVVMパターンに基づいて、以下のようにコードを再構成しました:
ViewModel
View
Model
App Entry
これで、MVVMパターンに従った構成となります。ViewModelがデータの管理を行い、Viewはそのデータを表示する役割を担っています。