現在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)
を設定してあげる必要があるみたいです。
以上です。