1. List 列表视图实现增删改操作
/// 列表视图
struct ListBootcamp: View {
/// 水果
@State var fruits: [String] = [
"apple", "orange", "banana", "peach"
]
/// 蔬菜
@State var veggies: [String] = [
"tomato", "potato", "carrot"
]
var body: some View {
/// 导航控制器
NavigationView{
List{
Section {
ForEach(fruits, id: \.self) { fruit in
Text(fruit.capitalized) // capitalized: 以单词形式显示
.font(.caption)
.foregroundColor(.white)
//.frame(maxWidth: .infinity, maxHeight: .infinity)
//.background(Color.red)
.padding(.vertical)
}
// 删除行
.onDelete(perform: deleted)
// 移动行
.onMove(perform: moved)
// 列表行背景
.listRowBackground(Color.blue)
} header: {
HStack {
Text("Fruits")
Image(systemName: "flame.fill")
}
.font(.headline)
.foregroundColor(.orange)
}
Section {
ForEach(veggies, id: \.self) { veggie in
Text(veggie.capitalized)
}
} header: {
Text("Veggies")
.font(.headline)
.foregroundColor(.purple)
}
}
.accentColor(.purple)
//.listStyle(.sidebar)
//.navigationBarHidden(false)
.navigationTitle("Grocery List")
.navigationBarItems(leading: EditButton(), trailing: addButton)
}
.accentColor(.red)
}
// 添加按钮
var addButton: some View{
Button("Add") {
add()
}
}
// 删除行
func deleted(indexSet: IndexSet){
fruits.remove(atOffsets: indexSet)
}
// 移动行
func moved(indices: IndexSet, newOffset: Int){
fruits.move(fromOffsets: indices, toOffset: newOffset)
}
// 添加行
func add(){
fruits.append("Coconut")
}
}
2. 效果图: