【问题标题】:Xcode: Swift - How to save drag and drop tableview cell positions (core data)?Xcode:Swift - 如何保存拖放表格视图单元格位置(核心数据)?
【发布时间】:2021-10-10 03:04:45
【问题描述】:

我对快速开发很陌生。在拖放单元格后,我需要一些帮助保存单元格的位置。问题是我可以毫无问题地拖放单元格。但是,当我导航到其他视图控制器或关闭并重新打开模拟器时,单元格会重置为旧位置

我按照另一个 stackoverflow 答案来执行此操作,但找不到与我的问题相关的任何答案。我已经发布了我用来执行拖放功能的代码。感谢您的帮助,谢谢。

var notes = [Notes]()
var managedObjectContext: NSManagedObjectContext!

@IBOutlet weak var tableview: UITableView!


override func viewDidLoad() {
    super.viewDidLoad()
    
    managedObjectContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    
    tableview.dragDelegate = self
    tableview.dropDelegate = self
    tableview.dragInteractionEnabled = true
}

override func viewWillAppear(_ animated: Bool) {
    self.tableview.reloadData()
    loadData()
}

func tableView(_ tableView: UITableView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] {
    let dragItem = UIDragItem(itemProvider: NSItemProvider())
    dragItem.localObject = notes[indexPath.row]
    return [ dragItem ]
}

func tableView(_ tableView: UITableView, performDropWith coordinator: UITableViewDropCoordinator) {
    
}


 func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
    let mover = notes.remove(at: sourceIndexPath.row)
    notes.insert(mover, at: destinationIndexPath.row)
    
    
    tableview.reloadData()

}

更新 1:我试过了,但没有用

 func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: 
 IndexPath, to destinationIndexPath: IndexPath) {
    let mover = notes.remove(at: sourceIndexPath.row)
    notes.insert(mover, at: destinationIndexPath.row)

    do{
                try notes.managedObjectContext.save()
            } catch {
                print("Rows could not be saved")
            }




    
 

【问题讨论】:

    标签: ios swift xcode uiviewcontroller uikit


    【解决方案1】:

    我看到有一个loadData() 方法,但看不到它的实际作用。

    我猜loadData() 方法是否从 Core Data 加载您的数据并存储到 notes 数组?如果是这样,那么它应该是问题所在。由于你修改了notes(通过调用notes.remove()notes.insert()),但是你还没有将notes保存到Core Data,所以在viewVillAppear中的loadData()被调用之后,你从Core加载原始数据再次向notes 发送数据。

    要修复它,您应该在 notes.insert() 之后将 notes 保存到 Core Data。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多