SwiftUI - List的基本使用,及分组、编辑、添加、删除功能
SwiftUI - List
List是对UITableView的封装。本章包含List的基本使用,及分组、编辑、添加、删除功能
基本使用
// ListViewDemo1.swift
struct ListViewDemo1 : View {
var body: some View {
NavigationView{
List{
NavigationLink(destination: FirstDetailView()){
Text("第1行")
}
NavigationLink(destination: SecondDetailView()){
Text("第2行")
}
}
}
}
}
List分组
// ListViewDemo2.swift
struct ListViewDemo2 : View {
var body: some View {
List{
Section(header: Text("我是头"), footer: Text("我是🦶")) {
Text("我是第一行")
Text("我是第二行")
}
Section{
Text("我是第一行")
Text("我是第二行")
}
}
.listStyle(GroupedListStyle())
}
}
List编辑、添加、删除、移动Item
// ListViewDemo3.swift
struct ListViewDemo3 : View {
@State var items : [Item] = [
Item(name: "第1行"),
Item(name: "第2行"),
Item(name: "第3行")
]
func addItem() {
items.append(Item(name:"第\(self.items.count + 1)行"))
}
var body: some View {
List{
//使用ForEach,需要保证Item遵守Hashable协议
ForEach(items){ item in
Text(item.name)
}
.onDelete{ index in //也可以这样写😎
self.items.remove(at: index.first!)
}
.onMove{ from,to in
if from.first! != to {
//交换位置
//self.items.swapAt(from.first!, to - 1)
//移动位置
self.items.move(fromOffsets: from, toOffset: to)
}
}
}.navigationBarItems(trailing: HStack{
Button(action: addItem){
Text("添加")
}
EditButton()
})
}
}
- 编辑功能通过EditButton启用;
- 删除Item通过onDelete实现
- 移动Item通过onMove实现