研究了一下SwiftUI的List。使用自带的编辑模式能简便的实现很多功能。
主要涉及:
- onDrag
- onMove
- onDelete
- swipeActions
效果如图:
使用编辑模式
打开编辑模式的环境变量,list就进入到编辑模式中。
.environment(\.editMode, $editMode)
之后添加 onDrag/onMove/onDelete 来实现移动及删除。
示例代码如下:
import SwiftUI
struct DDragList: View {
@State var datas: [(String,[String])] = [("诗歌", ["黄瓜不只", "是黄瓜", "今天天气", "还是不错的"]),
("古诗词", ["床前明月光", "疑是地上霜", "举头望明月", "低头思故乡"])]
@State var editMode: EditMode = .inactive
var body: some View {
List {
ForEach(datas.indices, id: \.self) { index in
Section(datas[index].0) {
var subs = datas[index].1
ForEach(subs, id: \.self) { sub in
Text(sub)
.onDrag {
let provider = NSItemProvider.init(object: NSString(string: sub))
return provider
}
}
.onMove { fromSet, to in
subs.move(fromOffsets: fromSet, toOffset: to)
datas[index].1 = subs
}
.onDelete { indexSet in
subs.remove(atOffsets: indexSet)
datas[index].1 = subs
}
}
}
}
.environment(\.editMode, $editMode)
.onAppear {
editMode = .active
}
.onDisappear {
editMode = .inactive
}
}
}
struct DDragList_Previews: PreviewProvider {
static var previews: some View {
DDragList()
}
}
使用swipeAction
不进入List编辑模式,通过横滑列表项展示编辑按钮方式来实现编辑List。
swipeAction中的content需要是Button
.swipeActions(edge: .trailing, allowsFullSwipe: true) {Button()}
示例代码如下:
import SwiftUI
struct DDragListSwipeAction: View {
@State var datas: [(String,[String])] = [("诗歌", ["黄瓜不只", "是黄瓜", "今天天气", "还是不错的"]),
("古诗词", ["床前明月光", "疑是地上霜", "举头望明月", "低头思故乡"])]
var body: some View {
List {
ForEach(datas.indices, id: \.self) { index in
Section(datas[index].0) {
var subs = datas[index].1
ForEach(subs, id: \.self) { sub in
Text(sub)
.onDrag {
let provider = NSItemProvider.init(object: NSString(string: sub))
return provider
}
.swipeActions(edge: .trailing, allowsFullSwipe: true) {
Button {
let offset = subs.firstIndex(of: sub)
subs.remove(at: offset!)
datas[index].1 = subs
} label: {
Image(systemName: "trash")
}
.tint(.red)
Button {
print("edit")
} label: {
Image(systemName: "square.and.pencil")
}
.tint(.orange)
}
}
.onMove { fromSet, to in
subs.move(fromOffsets: fromSet, toOffset: to)
datas[index].1 = subs
}
}
}
}
}
}
struct DDragListSwipeAction_Previews: PreviewProvider {
static var previews: some View {
DDragListSwipeAction()
}
}