Ios 改变单元格的索引
我开始使用UITableView,但似乎无法找到如何使用代码更改单元格的位置。改变故事板中的位置非常简单,但我需要能够快速完成 TLDR强>Ios 改变单元格的索引,ios,swift,uitableview,Ios,Swift,Uitableview,我开始使用UITableView,但似乎无法找到如何使用代码更改单元格的位置。改变故事板中的位置非常简单,但我需要能够快速完成 TLDR 更新您的数据。i、 e.swap(&arr[2]、&arr[3]) 调用tableView的reloadData()方法来反映对数据的更改 长答案 UITableView的实例通过检查其数据源(UITableViewDataSource)来获取所需信息。这包括节数和行数,以及表视图要使用的UITableViewCell实例。这些由以下UITableViewDa
swap(&arr[2]、&arr[3])
reloadData()
方法来反映对数据的更改UITableView
的实例通过检查其数据源(UITableViewDataSource
)来获取所需信息。这包括节数和行数,以及表视图要使用的UITableViewCell
实例。这些由以下UITableViewDataSource
delegate方法定义:
override func numberOfSectionsInTableView(tableView: UITableView) -> Int;
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int;
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell;
通常,您会将前两种方法基于您拥有的一些数据,可能是一个数组或类似的容器。例如,如果您的tableView显示了名为水果数组
(其中包含不同水果的名称-字符串列表)的数组中的数据,则您可能会遇到以下情况:
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// Our array is one dimensional, so only need one section.
// If you have an array of arrays for example, you could set this using the number of elements of your child arrays
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Number of fruits in our array
return fruitArray.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("yourCellId") // Set this in Interface Builder
cell.textLabel?.text = fruitArray[indexPath.row]
return cell
}
然后,您可以看到您的问题的答案变得简单!由于给定单元格的内容基于数组
,因此只需更新数组即可。但是如何让tableView“重新检查”其数据源呢?那么,您可以使用reloadData
方法,如下所示:
swap(&fruitArray[2], &fruitArray[3])
tableView.reloadData()
然后,这会触发tableView“重新检查”其数据源,从而导致数据交换显示在屏幕上
如果希望用户能够交换单元格的位置,可以使用以下UITableViewDelegate(而不是UITableViewDataSource
)委托方法:
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool
查看以获取更多信息。您还可以在和上查看苹果的文档,以了解更多详细信息
希望这有帮助 我假设您正在谈论更改tableview中单元格的索引/顺序。您需要更改tableview数据源中单元格数据的顺序,然后调用
tableview.reloadData()
非常感谢您,Jason,这是非常彻底和有用的!