0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

SwiftUIの基本:リストの編集・追加・削除・並び替えの実装を簡単に説明してみました!🔰

0
Posted at

SwiftUIでは、非常にシンプルなコードでリストの「追加」「削除」「並び替え」「編集モード」などを実装することができます。この記事では、以下の4つの基本機能を実装する方法を丁寧に解説します。

  • アイテムの追加(Add)

  • アイテムの削除(Delete)

  • アイテムの並び替え(Move)

  • 編集モード(Edit)

基本構造:Listとデータの準備

import SwiftUI

struct ContentView: View {
    @State var items = ["Apple", "Banana", "Orange"]
    @State var newItem = ""

    var body: some View {
        NavigationStack {
            VStack {
                HStack {
                    TextField("新しいアイテム", text: $newItem)
                        .textFieldStyle(RoundedBorderTextFieldStyle())
                    Button("追加") {
                        addItem()
                    }
                }
                .padding()

                List {
                    ForEach(items, id: \.self) { item in
                        Text(item)
                    }
                    .onDelete(perform: deleteItems)
                    .onMove(perform: moveItems)
                }
                .navigationTitle("フルーツ一覧")
                .toolbar {
                    EditButton() // 編集ボタンを追加
                }
            }
        }
    }

    // 追加機能
     func addItem() {
        guard !newItem.isEmpty else { return }
        items.append(newItem)
        newItem = ""
    }

    // 削除機能
     func deleteItems(at offsets: IndexSet) {
        items.remove(atOffsets: offsets)
    }

    // 並び替え機能
     func moveItems(from source: IndexSet, to destination: Int) {
        items.move(fromOffsets: source, toOffset: destination)
    }
}

各機能のポイント解説

1.追加(Add)

 @State var newItem = ""

 TextField("新しいアイテム", text: $newItem)
Button("追加") {
    addItem()
}


 func addItem() {
        guard !newItem.isEmpty else { return }
        items.append(newItem)
        newItem = ""
    }

TextFieldに入力された内容を@Stateで管理し、append()でリストに追加します。

2.削除(Delete)

.onDelete(perform: deleteItems)

func deleteItems(at offsets: IndexSet) {
       items.remove(atOffsets: offsets)
   }

ListのForEachに.onDeleteを付けることで、スワイプ削除が可能になります。

3.並び替え(Move)

.onMove(perform: moveItems)

func moveItems(from source: IndexSet, to destination: Int) {
        items.move(fromOffsets: source, toOffset: destination)
    }

長押しでドラッグし、アイテムを並び替えることができます。

4.編集モード(Edit)

.toolbar {
    EditButton()
}

EditButton()を配置するだけで、削除と並び替えができる編集モードが使えます。

まとめ

コードでリストの追加・削除・並び替え・編集は、アプリのToDoリストや買い物リスト、学習リストなど、さまざまなシーンで役立つ機能なので、ぜひ学習してみてください!✌️

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?