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()
}
效果图: