Skip to main content
 首页 » 数据库

ios之在两个部分之间移动 UITableViewCell ios Swift

2024年01月01日69leader

我正在使用两个部分,例如, 第 1 节与 单元格 0 单元格 1 单元格 3 和 第 2 节与 单元格 0 单元格 1 单元格 3

但我想将第 1 部分第 2 部分的单元格 0 移动到第 1 部分 任何人都可以使用快速编程用代码解释我

请您参考如下方法:

基本上,您需要了解数据源需要在单元格交换之前更新,否则会发生崩溃。

看下面的例子:

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { 
 
    var data : [[String]] = [["Mike", "John", "Jane"], ["Phil", "Tania", "Monica"]] 
 
    @IBOutlet weak var tableView: UITableView! 
    func numberOfSectionsInTableView(tableView: UITableView) -> Int { 
        return data.count 
    } 
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
        return data[section].count 
    } 
 
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
 
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as UITableViewCell 
        let name = data[indexPath.section][indexPath.row] 
        (cell.viewWithTag(22) as UILabel).text = "(" + String(indexPath.section) + ":" + String(indexPath.item) + ") " + name 
 
        return cell 
    } 
 
    @IBAction func pressed(sender: UIButton) { 
 
        // arbitrarily define two indexPaths for testing purposes 
        let fromIndexPath = NSIndexPath(forRow: 0, inSection: 0) 
        let toIndexPath = NSIndexPath(forRow: 0, inSection: 1) 
 
        // swap the data between the 2 (internal) arrays 
        let dataPiece = data[fromIndexPath.section][fromIndexPath.row] 
        data[toIndexPath.section].insert(dataPiece, atIndex: toIndexPath.row) 
        data[fromIndexPath.section].removeAtIndex(fromIndexPath.row) 
 
        // Do the move between the table view rows 
        self.tableView.moveRowAtIndexPath(fromIndexPath, toIndexPath: toIndexPath) 
 
 
    } 
} 

这里我有一个最简单的二维数组,其中包含一些名称。我将其定义为 [[String]] 以避免稍后强制转换它。在我的 Storyboard 之前,我有一个称为“按下”的按钮。我交换数据源,然后调用 moveRowAtIndexPath。