SwiftUI开发必学!List实现左滑删除、位置移动!
B站视频:https://www.bilibili.com/video/BV1pt421J7LZ
学会如何利用SwiftUI的List组件实现对列表内容的左滑删除和位置移动!
import SwiftUI
struct ContentView: View {
@State private var colorList: [Color] = [.pink, .green, .purple, .yellow, .orange]
@State private var isEditing = false
var body: some View {
NavigationView {
List {
ForEach(colorList, id: \.self) { color in
ItemView(color: color)
}
.onDelete(perform: { indexSet in
colorList.remove(atOffsets: indexSet)
})
.onMove(perform: { indices, newOffset in
colorList.move(fromOffsets: indices, toOffset: newOffset)
})
}
.navigationTitle("List")
.navigationBarItems(trailing: MyEditButton(isEditing: $isEditing))
.environment(\.editMode, .constant(isEditing ? .active : .inactive))
}
}
}
struct ItemView: View {
@State var color: Color
var body: some View {
HStack {
Circle()
.frame(width: 45)
VStack (alignment: .leading, content: {
RoundedRectangle(cornerRadius: 5)
.frame(width: 150, height: 5)
RoundedRectangle(cornerRadius: 5)
.frame(width: 100, height: 5)
})
Spacer()
}
.foregroundColor(color)
}
}
struct MyEditButton: View {
@Binding var isEditing: Bool
var body: some View {
Button(action: {
withAnimation {
isEditing.toggle()
}
}, label: {
Text(isEditing ? "Done" : "Edit")
})
}
}
#Preview {
ContentView()
}
License:
CC BY 4.0