0
2

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でリストの要素を横スライドで削除する方法

Posted at

現在SwiftUIを勉強中なので、さまざまなUIを実装しています。
今回は、SwiftUIでリストの要素を横スライドで削除する実装をしてみました。

Xcode Version 14.2

EditListView.swift

struct EditListView: View {
    @State private var tee = ["緑茶", "烏龍茶", "ほうじ茶", "ジャスミン茶", "麦茶", "烏龍茶", "ほうじ茶", "ジャスミン茶", "麦茶", "烏龍茶", "ほうじ茶", "ジャスミン茶", "麦茶", "烏龍茶", "ほうじ茶", "ジャスミン茶", "麦茶", "烏龍茶", "ほうじ茶", "ジャスミン茶", "麦茶"]
    
    var body: some View {
        VStack(spacing: 0) {
            Divider().background(Color.brown).padding(.top, 10)
            List {
                ForEach(tee, id: \.self) { tee in
                        VStack(alignment: .center ,spacing: 0) {
                            Text(tee)
                                .font(.system(size: 16))
                                .frame(maxWidth: .infinity, alignment: .leading)
                        }.listRowInsets(EdgeInsets())
                }
                .onDelete(perform: remove)
            }
            .listStyle(PlainListStyle())
        }
    }
    
    /// 行削除処理
    func remove(index: IndexSet) {
        tee.remove(atOffsets: index)
    }
}

スライドで削除する処理はこちらになります。

.swift
func remove(index: IndexSet) {
    tee.remove(atOffsets: index)
}

リストに削除機能を実装するには
.onDelete(perform: remove)
を設定してあげる必要があるみたいです。

スクリーンショット 2023-08-06 21.29.20.png

以上です。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?