2
8

More than 3 years have passed since last update.

SwiftUI .onMoveの実装について ~CoreData~

Posted at

環境

【Xcode】 12.4
【Swift】 5.3.2
【iOS】 14.5

ソースコード

Todoアプリ作成の過程で少々面倒だったため記録用。
.onMoveを実装するにあたりCoreDataを使用。

まずはCoreDataを使えるようにします。

struct ContentView: View {
   @Environment(\.managedObjectContext) private var viewContext
   @FetchRequest(sortDescriptors: [NSSortDescriptor(keyPath: \todoList.data,ascending:true)],animation:.default)

   private var todoList: FetchedResults<TodoEntity>
}

move関数の実装

    private func move(from source: IndexSet, to destination: Int) {
        //下から上に並べ替え時の挙動
        if source.first! > destination {
            todoList[source.first!].data = todoList[destination].data - 1
            for i in destination...todoList.count - 1 {
                todoList[i].data = todoList[i].data + 1
            }
        }

        //上から下に並べ替え時の挙動
        if source.first! < destination {
            todoList[source.first!].data = todoList[destination - 1].data + 1
            for i in 0...destination - 1 {
                todoList[i].data = todoList[i].data - 1
            }
        }
      saveData()
    }

    private func saveData() {
        try? self.viewContext.save()
    }

.onMoveの実装

    var body: some View {
        NavigationView {
            VStack {
                List {
                    ForEach(todoList, id: \.id) { todo in
                        if todo.category == self.category.rawValue {
                            NavigationLink(destination: EditTask(todo: todo))
                        } //一部抜粋
                      }
                    }
                    .onDelete(perform: deleteTodo)
                    .onMove(perform: move)
                }
                .toolbar {
                    EditButton()
                }
            }
        }
    }

参考資料

2
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
8