SwiftUI的ListView

本文介绍了如何在SwiftUI中使用ListView展示水果和蔬菜列表,包括配置Section、ForEach循环、删除和移动功能,以及自定义添加按钮和accentColor。
摘要由CSDN通过智能技术生成

SwiftUI的ListView

记录下ListView的一些基础配置


import SwiftUI

struct ListviewBootCamp: View {
    @State var fruits = ["aple", "orange", "banana", "peach"]
    @State var veggies = ["tomato", "potato", "carrot",]
    
    var body: some View {
        NavigationView(content: {
            List {
                Section(
                    header: HStack {
                        Text("Fuirts")
                        Image(systemName: "flame.fill")
                    }
                        .font(.title3)
                        .foregroundColor(.purple)
                ) {
                    ForEach(fruits, id: \.self) { fruits in
                        /// 首字母大写
                        Text(fruits.capitalized)
                            .font(.caption)
                            .foregroundColor(.white)
                            .padding(.vertical)
                            
                    }
                    .onDelete(perform: delete)
                    .onMove(perform: move)
                    .listRowBackground(Color.green)
                }
                
                Section(
                    header: Text("veggies".capitalized)) {
                    ForEach(fruits, id: \.self) { fruits in
                        /// 首字母大写
                        Text(fruits.capitalized)
                    }
                }
            }
            /// 列表样式
//            .listStyle(DefaultListStyle())
//            .listStyle(GroupedListStyle())
//            .listStyle(InsetListStyle())
//            .listStyle(PlainListStyle())
            .listStyle(SidebarListStyle())
//            .listStyle(InsetGroupedListStyle())
//            .listStyle(GroupedListStyle())
            .navigationTitle("ListviewBootCamp")
            .navigationBarTitleDisplayMode(.inline)
            .navigationBarItems(leading: EditButton(),
                                trailing: addButton
            )
        }
        
        ) 
        /// 强调按钮颜色
        .accentColor(.red)
       
    }
    
    var addButton: some View {
        Button("Add", action: {
            add()
        })
    }
    
    func delete(indexSet: IndexSet) {
        fruits.remove(atOffsets: indexSet)
        print("delete: \(fruits)")
    }
    
    func move(indices: IndexSet, newOffset: Int) {
        self.fruits.move(fromOffsets: indices, toOffset: newOffset)
        print("delete: \(fruits)")
    }
    
    func add() {
        fruits.append("watermelon")
    }
}

#Preview {
    ListviewBootCamp()
}

效果图:请添加图片描述

  • 6
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值