xcode iOS UITableView 在代码中移动单元格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49554820/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 10:35:31  来源:igfitidea点击:

iOS UITableView move Cells in Code

iosswiftxcodeuitableview

提问by SirJoe

I recently started working on a small iOSProject where I have a Game Score Leaderboard represented by a UITableView, whenever the Player gets a new Highscore the Leaderboard gets visible and his Score Entry (Including Picture, Name and Score) represented by a UITableViewCellis supposed to move to the new right Spot in the TableViewLeaderboard it now belongs to. The calculation of the new indexis working fine but the cellis not moving at all.

我最近开始做一个小iOS项目,我有一个由 a 表示的游戏分数排行榜UITableView,每当玩家获得一个新的高分时,排行榜就会出现,并且他的分数条目(包括图片、名称和分数)由 aUITableViewCell表示应该移动到TableView它现在所属的排行榜中新的正确位置。新的计算index工作正常,但cell根本没有移动。

Some info:

一些信息:

  • The Leaderboard is populated succesful,

  • I set the func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Boolto true

  • Also implemented the func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath)

  • 排行榜填充成功,

  • 我设置func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool为真

  • 还实施了 func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath)

correctly.

正确。

I am thinking that maybe I am missing something but the problem could also lie somewhere else, I don't know and would really appreciate some help.

我在想,也许我遗漏了一些东西,但问题也可能出在其他地方,我不知道并且非常感谢一些帮助。

Delegate Mehods for Editing

委托编辑方法

func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
    return true
}
// Handles reordering of Cells
func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
    let player = players[sourceIndexPath.row]
    players.remove(at: sourceIndexPath.row)
    players.insert(player, at: destinationIndexPath.row)
}

Code where I try to move Row

我尝试移动行的代码

func newHighscore(highscore: Int) {
    friendsTableView.reloadData()
    let myNewIndex = Player.recalculateMyIndex(players: players, score: highscore)
    friendsTableView.moveRow(at: [0,Player.myIndex], to: [0,myNewIndex])

}

回答by Sergey Hleb

This code works, but it only example. adapt it for you. create new file and put this code in it, build it and check.

此代码有效,但只是示例。为你调整它。创建新文件并将此代码放入其中,构建并检查。

class ViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!


    var scores = ["1", "2", "3", "4", "5"]

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    func move(from: IndexPath, to: IndexPath) {
        UIView.animate(withDuration: 1, animations: {
            self.tableView.moveRow(at: from, to: to)
        }) { (true) in
            // write here code to remove score from array at position "at" and insert at position "to" and after reloadData()
        }
    }

    @IBAction func buttonPressed(_ sender: UIButton) {
        let fromIndexPath = IndexPath(row: 4, section: 0)
        let toIndexPath = IndexPath(row: 1, section: 0)
        move(from: fromIndexPath, to: toIndexPath)
    }
}

extension ViewController: UITableViewDelegate, UITableViewDataSource {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return scores.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as? TableViewCell
        if let cell = cell {
            cell.setText(text: scores[indexPath.row])
        }
        return cell ?? UITableViewCell()
    }

    func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        return true
    }

}   

For correctly use, you need to insert new element in array at last, reload data and after you can call method move() and put in it current indexPath and indexPath to insert you need.

为了正确使用,您需要最后在数组中插入新元素,重新加载数据,然后您可以调用方法 move() 并将其放入当前的 indexPath 和 indexPath 以插入您需要的。

回答by AtulParmar

Try this code for move row Up/Down

试试这个代码向上/向下移动行

var longPress = UILongPressGestureRecognizer (target: self, action:#selector(self.longPressGestureRecognized(_:)))                 
ToDoTableView.addGestureRecognizer(longPress)

//MARK: -longPressGestureRecognized

//MARK: -longPressGestureRecognized

 func longPressGestureRecognized(_ gestureRecognizer: UIGestureRecognizer) {

    let longPress = gestureRecognizer as! UILongPressGestureRecognizer
    let state = longPress.state
    let locationInView = longPress.location(in: ToDoTableView)
    let indexPath = ToDoTableView.indexPathForRow(at: locationInView)

    struct Path {
        static var initialIndexPath : IndexPath? = nil
    }

    switch state {
    case UIGestureRecognizerState.began:
        if indexPath != nil {
            let cell = ToDoTableView.cellForRow(at: indexPath!) as UITableViewCell!
            UIView.animate(withDuration: 0.25, animations: { () -> Void in
                cell?.alpha = 0.0
            }, completion: { (finished) -> Void in
                if finished {
                    UIView.animate(withDuration: 0.25, animations: { () -> Void in
                        cell?.alpha = 1
                    })
                } else {
                    cell?.isHidden = true
                }
            })
        }
    case UIGestureRecognizerState.changed:

        if ((indexPath != nil) && (indexPath != Path.initialIndexPath)) {
            itemsArray.insert(itemsArray.remove(at: Path.initialIndexPath!.row), at: indexPath!.row)
            ToDoTableView.moveRow(at: Path.initialIndexPath!, to: indexPath!)
            Path.initialIndexPath = indexPath
        }
    default:
        print("default:")
    }
}