import SwiftUI
import SwiftData
import Algorithms
import Foundation
@Model
final class Memo {
var id: String
var order: Int
var content: String
init(content: String, order: Int = 0) {
self.id = ""
self.content = content
self.order = order // 初期値として0を設定
}
}
struct ContentView: View {
@Environment(\.modelContext) private var modelContext
@Query(sort: [SortDescriptor(\Memo.order)]) private var memos: [Memo]
var body: some View {
NavigationStack {
List{
ForEach(memos, id: \.self){ memo in
NavigationLink(memo.content, destination: MemoDetailView(memo: .constant(memo))
)
}
.onMove(perform: moveMemo)
}
.toolbar{
ToolbarItem(placement: .navigationBarTrailing){
NavigationLink(destination:
MemoDetailView(memo:.constant(Memo(content: "")
)
)
){
Image(systemName: "plus")
}
}
ToolbarItem(placement: .navigationBarTrailing) { // EditButtonをナビゲーションバーの左側に配置
EditButton()
}
}
}
}
private func moveMemo(from source: IndexSet, to destination: Int) {
var orderedMemos = memos.sorted(by: { $0.order < $1.order }) // orderで並び替え
// 並び替えを実行
orderedMemos.move(fromOffsets: source, toOffset: destination)
// 更新された順序をmodelContextに反映
for (index, memo) in orderedMemos.enumerated() {
if let existingMemo = memos.first(where: { $0.id == memo.id }) {
existingMemo.order = index
}
}
saveContext()
}
// コンテキストの保存を行う関数
private func saveContext() {
do {
try modelContext.save()
} catch {
print("コンテキストの保存に失敗しました: \(error.localizedDescription)")
}
}
}