Skip to main content

SwiftUI专辑018-移动List中的rows

· 预计阅读2分钟

headerimg 本章我们将实现一个List, 允许用户移动,重新组织rows。

Getting ready

首先创建一个新的SwiftUI项目MovingListRows

How to do it…

  1. 还是准备数据
@State var countries = ["USA", "Canada", "England", "Cameroon", "South Africa", "Mexico" , "Japan", "South Korea"]
  1. 构建一个NavigationView, EditButton, List,只是ForEach的时候我们添加上onMove
struct ContentView: View {
@State var countries = ["USA", "Canada", "England", "Cameroon", "South Africa", "Mexico" , "Japan", "South Korea"]
var body: some View {
NavigationView {
List {
ForEach(countries, id: \.self) { country in
Text(country)
}.onMove(perform: self.moveRow)
}.navigationTitle("Countries")
.navigationBarTitleDisplayMode(.inline)
.navigationBarItems(trailing: EditButton())
}
}

private func moveRow(source: IndexSet, destination: Int){

}
}
  1. 实现moveRow
private func moveRow(source: IndexSet, destination: Int){   
countries.move(fromOffsets: source, toOffset: destination)
}

当我们点击Edit时

image-20211226171317473

How it works…

首先我们需要一个EditButton来进入编辑模式。

在ForEach时,我们提供onMove这个modifier,当我们移动时会触发对应回调。

moveRow函数有两个参数,sourcedestination。分别代表当前index和移动后的index。

在回调中,我们修改数据源移动数据位置。