SwiftUI之List

本文详细介绍了SwiftUI中List的使用,包括动态内容的添加、点击事件、分组列表、侧滑删除、动态列表、单选与多选功能,以及拖动重排等操作。通过实例展示了如何创建导航链接、设置组头和组尾,以及去除导航箭头的方法。此外,还讨论了List的不同样式和宽度设置技巧。
摘要由CSDN通过智能技术生成

在SwiftUI中使用List可以非常方便快速的制作各种列表.List其实就是对UITableView进行的封装。

List的工作是提供数据滚动表。它与Form几乎相同,只是List用于显示数据而Form是请求用户输入。

List可是静态,动态,动静混合,与Section一起使用。

在List中添加动态内容,我们可以使用两种方式:

  • 直接使用List自己提供的动态内容构造方法 

var str:[String]=["1","2","3","4","5"]

    var body: some View{

   return     List(str,id:\.self){ item in

                       Text(item)

       }.onTapGesture(count: 1) {

          print("s")

       }

 在List中使用ForEach:使用ForEach可以在同一List中,添加多个动态源,且可添加静态内容,对于动态内容可以控制版式

  List{

        ForEach(0..<str.count,id:\.self){ index in

                                Text(self.str[index])

                    }

        }

    }

 点击cell跳转到不同的页面:其中one和Two都是view页面

import SwiftUI

struct HomeView:View {

    var body: some View{

        return List{

                    ForEach(0..<3, id: \.self) { index in

                        if index==0{

                            //根据数组的索引,创建导航按钮,并设置导航按钮的目标视图为自定义的DetailView

                            NavigationLink(destination: one.init(name: "", age: 1)){

                                Text("\(index)")

                            }

                        }

                        if index==1{

                            NavigationLink(destination: Two()){

                                Text("\(index)")

                            }

                        }

                       }

                   }

      }

}

 section组头和组尾

import SwiftUI

struct HomeView:View {

    var body: some View{

        return List{

            Section(header:Text("some streets one"), footer: Text("Fotter1")){

                    ForEach(0..<3, id: \.self) { index in

                            NavigationLink(destination: one.init(name: "", age: 1)){

                                Text("\(index)")

                            }

                     }

               }

            Section(header:Text("some streets two"), footer: Text("Fotter2")){

                ForEach(0..<3, id: \.self) { index in

                        NavigationLink(destination: one.init(name: "", age: 1)){

                            Text("\(index)")

                        }

                   }

                }

        }.listStyle(GroupedListStyle())// 设置分组的样式

   }

}

侧滑删除

import SwiftUI

struct HomeView:View {

    @State var str:[Int]=[1,2,3,4,5,6,7,8]

    var body: some View{

        func deleteRow(at offsets:IndexSet) {

            str.remove(at Offsets:offsets)

               }

        return List{

            Section(header:Text("some streets one"), footer: Text("Fotter1")){

                    ForEach(str, id: \.self) { index in

                            NavigationLink(destination: one.init(name: "", age: 1)){

                                Text("\(index)")

                            }

                    }.onDelete(perform: deleteRow)

               }

        }

   }

}

动态list:

//Identifiable用来标识List每一行的 row是唯一的,当去实现Identifiable 协议的时候,我们需要去实现一个 id 的属性,这个变量不一定需要是 Int 类型。这个协议只要求 id 的类型必须是 Hashable 的。(Int,Double,String等等这些都是Hashable的)
实现了Identifiable 协议之后,我们不再需要去告诉 List 我们数组元素中的元素(符合协议的)是如何标识唯一的。

import SwiftUI
struct Person: Identifiable,Hashable {
    var id:Int
    var name:String
    var age:Int
}
import SwiftUI

struct HomeView:View {
    var Persons = [
        Person(id:1,name:"lambo01",age:1),
        Person(id:2,name:"lambo02",age:2),
        Person(id:3,name:"lambo03",age:3),
        Person(id:4,name:"lambo04",age:4),
        Person(id:5,name:"lambo05",age:5),
        Person(id:6,name:"lambo06",age:6)
    ]
   
    var body: some View{
  //这里的id可以作为cell的唯一标识符,可以标识每一个row
        return List(Persons,id:\.id){ person in
            
            NavigationLink(destination:one()) {
                Text(person.name)
            }
        }
   }
}

单选:

import SwiftUI

struct HomeView:View {
   @State var indexs:[Int] = []//存储选中的索引
   @State var imagearr:[String]=["center","center","center","center","center","center"]//图片数组
    @State var color:[Color]=[.red,.red,.red,.red,.red,.red]// 背景颜色的数组
    var Persons = [
        Person(id:1,name:"lambo01",age:1),
        Person(id:2,name:"lambo02",age:2),
        Person(id:3,name:"lambo03",age:3),
        Person(id:4,name:"lambo04",age:4),
        Person(id:5,name:"lambo05",age:5),
        Person(id:6,name:"lambo06",age:6)
    ]
   
    var body: some View{
        
        return List(Persons,id:\.id){ person in

            HStack{
                Image(imagearr[person.id-1])
            Text(person.name).onTapGesture {

                for (value) in 0..<imagearr.count {
                    if value==person.id-1{
                        print("\(value)")
                        imagearr[person.id-1]="apple"
                        color[person.id-1] = .green
                    }else {
                        imagearr[value]="center"
                        color[value] = .red
                    }
                }
                print("\(indexs)")
            }.background(color[person.id-1])
          }
        }
   }
}

多选:

import SwiftUI
struct myModifier: ViewModifier {
    func body(content: Content) -> some View {
        content
            .foregroundColor(.red)
            .font(.title)
    }
}
struct HomeView:View {
   @State var indexs:[Int] = []//存储选中的索引
   @State var imagearr:[String]=["center","center","center","center","center","center"]//图片数组
    @State var color:[Color]=[.red,.red,.red,.red,.red,.red]// 背景颜色的数组
    var Persons = [
        Person(id:1,name:"lambo01",age:1),
        Person(id:2,name:"lambo02",age:2),
        Person(id:3,name:"lambo03",age:3),
        Person(id:4,name:"lambo04",age:4),
        Person(id:5,name:"lambo05",age:5),
        Person(id:6,name:"lambo06",age:6)
    ]
   
    var body: some View{
        
        return List(Persons,id:\.id){ person in

            HStack{
                Image(imagearr[person.id-1])
            Text(person.name).onTapGesture {
                if indexs.contains(person.id){
                    //swift中没有直接删除元素的方法,下面是用过滤的方式,然后再赋值给原来的数组,达到删除元素的目的
                    let filterArr  = indexs.filter {
                                $0 != person.id//数组中留下的元素都是不等于person.id
                                }
                    indexs=filterArr
                    imagearr[person.id-1]="center"
                    color[person.id-1] = .red
                }else {
                indexs.append(person.id)
                    imagearr[person.id-1]="apple"
                    color[person.id-1] = .green
                }
                print("\(indexs)")
            }.background(color[person.id-1])
          }
        }
   }
}

拖动cell改变位置:需要 EditButton()打开编辑功能。

import SwiftUI

struct Person: Hashable,Identifiable {
    var id:Int
    var name:String
    var age:Int
    }
import SwiftUI
struct HomeView:View {
   @State var indexs:[Int] = []//存储选中的索引
   @State var imagearr:[String]=["center","center","center","center","center","center"]//图片数组
    @State var color:[Color]=[.red,.red,.red,.red,.red,.red]// 背景颜色的数组
    @State  var Persons = [
        Person(id:1,name:"lambo01",age:1),
        Person(id:2,name:"lambo02",age:2),
        Person(id:3,name:"lambo03",age:3),
        Person(id:4,name:"lambo04",age:4),
        Person(id:5,name:"lambo05",age:5),
        Person(id:6,name:"lambo06",age:6)
    ]
   
    var body: some View{
        List{
            ForEach(Persons,id: \.self) {person in
            Text(person.name)
             }.onMove(perform: { from, to in
            Persons.move(fromOffsets: from, toOffset: to)
            print("\(Persons)")
            })
        }
        .navigationBarItems(trailing: HStack{
                    Button(action: addItem){
                        Text("添加")
                    }
                    EditButton()//这个是开始编辑功能,才能移动
                })
             }
    func addItem() {
        print("添加")
    }
}

List的几种模式:

DefaultListStyle、SidebarListStyle、InsetGroupedListStyle、GroupedListStyle、InsetListStyle、PlainListStyle

去掉右边箭头的做法:

//            将Text放置于NavigationLink上面即可去掉右边箭头,注意text要设置屏幕宽度
            ZStack{
                Text("one").frame(width: 375, height: 50, alignment: .leading)
                   NavigationLink(destination: arr.1, isActive: self.$isShow) {
                     
                               }
                
            }
import SwiftUI

struct Mine: View {
    @Environment(\.presentationMode) var presentationMode
    @State var isactive:Bool=false
    var arr=(Nextone(),Communitynext())
    var titlearr=["导航按钮切换","下拉刷新","上拉加载","个人信息","设置",""]
    @State var isShow = false
    var body: some View {
        List(){
            ForEach(titlearr,id:\.self){  title in
                if(title=="导航按钮切换"){
                    NavigationLink(
                        destination: arr.0,
                        label: {
                            Text("\(title)")
                           }
                    )
                }else     if(title=="下拉刷新"){
                    NavigationLink(
                        destination: arr.1,
                        label: {
                            Text("\(title)")
                           }
                    )
                }else     if(title=="上拉加载"){
                    NavigationLink(
                        destination: arr.0,
                        label: {
                            Text("\(title)")
                           }
                    )
                }else     if(title=="个人信息"){
                    NavigationLink(
                        destination: arr.0,
                        label: {
                            Text("\(title)")
                           }
                    )
                }else     if(title=="设置"){
                    NavigationLink(
                        destination: arr.0,
                        label: {
                            Text("\(title)")
                           }
                    )
                }
             

            将Text放置于NavigationLink上面即可去掉右边箭头,注意text要设置屏幕宽度
//            ZStack{
//                Text("one").frame(width: 375, height: 50, alignment: .leading)
//                   NavigationLink(destination: arr.1, isActive: self.$isShow) {
//
//                               }
//
//            }.background(Color.red)
         
                      }
        }.listStyle(.plain)
       }
}

List使用注意事项:宽度的设置和去掉右侧箭头

import SwiftUI

struct Mine: View {
    @Environment(\.presentationMode) var presentationMode
    @State var isactive:Bool=false
    var arr=(Navselect(),RefreshablePulldown(),RefreshView(),PersoninfoTop(),Nav(),Wordtransformsound())
    var titlearr=["导航按钮切换","下拉刷新","下刷上拉加载","个人信息","导航设置","文字转语音"]
    @State var isShow = false
    var body: some View {
        GeometryReader(content: { geometry in
        List(){
            ForEach(titlearr,id:\.self){  title in
                if(title=="导航按钮切换"){
                    NavigationLink(
                        destination: arr.0,
                        label: {
                            Text("\(title)")
                           }
                    )
                }else     if(title=="下拉刷新"){
                    NavigationLink(
                        destination: arr.1,
                        label: {
                            Text("\(title)")
                           }
                    )
                }else     if(title=="下刷上拉加载"){
                    NavigationLink(
                        destination: arr.2,
                        label: {
                            Text("\(title)")
                           }
                    )
                }else     if(title=="个人信息"){
                    NavigationLink(
                        destination: arr.3,
                        label: {
                            Text("\(title)")
                           }
                    )
                }else     if(title=="导航设置"){
                    NavigationLink(
                        destination: arr.4,
                        label: {
                            Text("\(title)")
                           }
                    )
                }else     if(title=="文字转语音"){
                    NavigationLink(
                        destination: arr.5,
                        label: {
                            Text("\(title)")
                           }
                    )
                }
             

//            将Text放置于NavigationLink上面即可去掉右边箭头,注意text要设置屏幕宽度
//            ZStack{
//                Text("one").frame(width: 375, height: 50, alignment: .leading)
//                   NavigationLink(destination: arr.1, isActive: self.$isShow) {
//                     }
//               }.background(Color.red)
         
                
            }
        }.listStyle(.plain)//这里必须要设置liststyle为plain,才能设置宽度和手机屏幕一样宽
                .frame(width: geometry.size.width, height: 500, alignment: .center)// 这里控制list的宽度
                .background(Color.gray)
            
        })
       }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值