SwiftUI - List的基本使用,及分组、编辑、添加、删除、移动功能

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()
        })
    }
}
  1. 编辑功能通过EditButton启用;
  2. 删除Item通过onDelete实现
  3. 移动Item通过onMove实现
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值