Swift 3 - 重新排列并保持tableview中的单元格

时间:2018-02-05 14:50:56

标签: uitableview core-data swift3 drag-and-drop

我有一个tableview,我可以添加项目,它将保存到核心数据,我也可以删除这些项目,一切正常

但是现在我想重新排列单元格并保留数据 目前我可以选择按钮编辑,它将允许我重新排列单元格,但是当我离开视图控制器时它会重置为如何

有人可以帮帮我吗?

class CustomWorkoutViewController: UIViewController {


@IBOutlet weak var newMusclesTableView: UITableView!

var workout:Workout?


override func viewDidLoad() {
    super.viewDidLoad()

    newMusclesTableView.delegate = self

    let nib = UINib(nibName: "muscleListTableViewCell", bundle: nil)
    newMusclesTableView.register(nib, forCellReuseIdentifier: "workCell")

}

override func viewDidAppear(_ animated: Bool) {
    self.newMusclesTableView.reloadData()
}



override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    if segue.identifier == "addMuscles"{
        guard let destination = segue.destination as? AddMusclesViewController else {
            return
        }
        destination.workout = workout

    }

    else if segue.identifier == "addLogs"{
        guard let destination = segue.destination as? WorkoutViewController,
            let selectedRow = self.newMusclesTableView.indexPathForSelectedRow?.row else {
                return
        }
        destination.muscleLog = workout?.muscleList?[selectedRow]
    }


}

func btnAction(_ sender: UIButton) {

    let point = sender.convert(CGPoint.zero, to: newMusclesTableView as UIView)
    let indexPath: IndexPath! = newMusclesTableView.indexPathForRow(at: point)

    let vc = viewMusclesViewController()
    let viewTitle = workout?.muscleList?[indexPath.row]

    vc.customInit(title: (viewTitle?.name)!)
    vc.titleStr = viewTitle?.name
    vc.gifStr = viewTitle?.muscleImage
    navigationController?.pushViewController(vc, animated: true)

}

@IBAction func editAction(_ sender: UIBarButtonItem) {

    self.newMusclesTableView.isEditing = !self.newMusclesTableView.isEditing
    sender.title = (self.newMusclesTableView.isEditing) ? "Done" : "Edit"

}


func deleteMuscle(at indexPath: IndexPath){
    guard let muscles = workout?.muscleList?[indexPath.row],
        let managedContext = muscles.managedObjectContext else{
            return
    }
    managedContext.delete(muscles)

    do{
        try managedContext.save()

        newMusclesTableView.deleteRows(at: [indexPath], with: .automatic)
    }catch{
        print("Could not save")
        newMusclesTableView.reloadRows(at: [indexPath], with: .automatic)
    }
}



override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

这是我的tableview扩展

extension CustomWorkoutViewController: UITableViewDelegate,UITableViewDataSource {

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return workout?.muscleList?.count ?? 0
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 70
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = newMusclesTableView.dequeueReusableCell(withIdentifier: "muscleCell", for: indexPath) as? muscleListTableViewCell

    cell?.cellView.layer.cornerRadius = (cell?.cellView.frame.height)! / 2


    if let muscles = workout?.muscleList?[indexPath.row]{
        cell?.muscleTitle?.text = muscles.name
        cell?.myBtn.addTarget(self, action: #selector(self.btnAction(_:)), for: .touchUpInside)

    }


    return cell!
}


func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete{
        deleteMuscle(at: indexPath)
    }
}

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

func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {

//How to persist data here?

}

}

2 个答案:

答案 0 :(得分:1)

您的代码决定使用此代码为行显示哪个项目:

if let muscles = workout?.muscleList?[indexPath.row]

行顺序将由muscleList中的顺序决定。当您使用其编辑模式时,表格视图可以重新排列单元格,但它无法保存新订单,因为它不知道如何更改muscleList的顺序。您的tableView(_:moveRowAt:to:)实现需要根据表视图更新来更改顺序。

如果muscleList是有序关系,请更改订单。如果它不是有序关系,那么您需要添加一个可用于对关系进行排序的属性 - 即使像sortOrder属性那样简单。

答案 1 :(得分:0)

我设法找到了解决自己问题的方法 如果有人需要帮助,我会在这里发布以供日后使用

func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
    let muscle = workout?.muscleList?[sourceIndexPath.row]
    workout?.removeFromRawMuscles(at: sourceIndexPath.row)
    workout?.insertIntoRawMuscles(muscle!, at: destinationIndexPath.row)

    do{
        try muscle?.managedObjectContext?.save()


    }catch{
        print("Rows could not be saved")
    }
}