本文可以学到如何在SwiftUI 中使用ListView编辑模式 去删除list里的元素
//
// ContentView.swift
// ListDemo
//
// Created by 飞 on 2023/6/14.
//
import SwiftUI
struct ContentView: View {
let fruit = ["Apple", "Orange", "Banana", "", ""]
var isEditingMode: Bool
/// Only available on iOS 15 and later
///
/// - parameters:
/// - isEditingMode: Set `true` if need swipe to delete, otherwise `false`.
///
init(isEditingMode: Bool) {
self.isEditingMode = isEditingMode
UITableView.appearance().backgroundColor = .clear
}
var body: some View {
if #available(iOS 15.0, *) {
List {
ForEach(fruit, id: \.self) { fruit in
FruitListItem(fruit:fruit)
.listRowBackground(
RoundedRectangle(cornerRadius: 8)
.foregroundColor(Color.green)
.background(Color.red)
)
.swipeActions(allowsFullSwipe: false) {
if isEditingMode {
Button(role: .destructive) {
print("Deleting conversation")
} label: {
Image(systemName: "trash.fill")
}
.tint(.red)
}
}
}
}
.modifier(ListBackgroundModifier())
} else {
EmptyView()
}
}
}
struct FruitListItem: View {
let fruit: String
var body: some View {
HStack(alignment: .center) {
RoundedRectangle(cornerRadius: 8)
.foregroundColor(Color.gray)
.frame(width: 40,height: 40)
.padding(.top, 8)
Text(fruit)
.font(.system(size: 17, weight: .medium))
.foregroundColor(.white)
}
.frame(height: 80)
}
}
struct ListBackgroundModifier: ViewModifier {
@ViewBuilder
func body(content: Content) -> some View {
if #available(iOS 16.0, *) {
content
.scrollContentBackground(.hidden)
} else {
content
.background(Color.gray)
}
}
}