6
7

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 3 years have passed since last update.

【SwiftUI】Listで削除Alertをだす

Last updated at Posted at 2020-02-24

SwiftUIでリストの削除時にアラートを出す方法です。

こうして

iPhone_11_—_13_3.png

こうするやつです

iPhone_11_—_13_3.png

ポイント

  1. onDeleteメソッドを使いますが、ListではなくForEachのメソッドなのでForEachを使います。
  2. alertモディファイアを使いますが、isPresentedではなく、itemを使います。(何こ目の要素かを取得するため)
  3. itemIdentifiableです。
import SwiftUI

struct ContentView: View {
    @State var deleteAlert:Bool = false
    @State var item: Item?
    
    func showDeleteAlert(offsets: IndexSet) {
        self.item = Item(id: String(offsets.first!))
    }
    
    struct Item: Identifiable {
        var id:String
    }
    
    var body: some View {
        List {
            ForEach(0..<5, id: \.self) { id in
                Text(String(id))
            }
            .onDelete(perform: showDeleteAlert)
            .alert(item: self.$item) { i in
                Alert(title: Text(i.id + "を削除しますか?"),
                      primaryButton: .destructive(Text("Delete")) {
                        // deleteの処理
                    },
                      secondaryButton: .cancel() {
                    }
                )
            }
        }
    }
}

参考

https://qiita.com/1amageek/items/e90e1cfb0ad497e8b27a
https://fuckingswiftui.com/#alert
https://www.hackingwithswift.com/books/ios-swiftui/using-alert-and-sheet-with-optionals

6
7
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
6
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?