0

如果我问错了这个问题或包含了太多代码,请原谅。我做的最后一次编程是在 amiga 和 Psion 组织者上使用 basic。所以我是 swift 的新手,甚至是堆栈溢出的新手。我正在使用来自各种来源的信息(Angela Yu、Ray Wenderlich、谷歌和堆栈溢出以及许多其他来源,但我感到很困惑。我正在尝试创建一个简单的数据库应用程序,并且已经实现了很多我想要的,但我可以'现在不使用滑动来删除或确实执行删除记录。我需要知道的是]我需要什么代码来执行单元格的滑动并删除与之关联的数据。我已经包含了我正在使用的功能直到我改变了一些东西。b]我认为我说得对

  import UIKit
import CoreData

class ViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!
    
    
//    var people: [NSManagedObject] = []
    var people = [DriverName]()
    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

    lazy var coreDataStack = CoreDataStack(modelName: "RDW_Monitor")
    var dataSource: UITableViewDiffableDataSource<String, DriverName>?
    fileprivate let driverCellIdentifier = "driverandRDWCell"
    
    lazy var fetchedResultsController: NSFetchedResultsController<DriverName> = {
        let fetchRequest: NSFetchRequest<DriverName> = DriverName.fetchRequest()
        let nameSort = NSSortDescriptor(key: #keyPath(DriverName.name), ascending: true)
        let rdwSort = NSSortDescriptor(key: #keyPath(DriverName.total), ascending: true)
        fetchRequest.sortDescriptors = [rdwSort, nameSort]
        
        let fetchedResultsController = NSFetchedResultsController(
            fetchRequest: fetchRequest,
            managedObjectContext: coreDataStack.managedContext,
            sectionNameKeyPath: nil,
            cacheName: "driverName")
        
        fetchedResultsController.delegate = self
        return fetchedResultsController
    }()
    
    
    var totalNumberOfDrivers = 0
    var vaughansTotal = 0

    
    override func viewDidLoad() {
        super.viewDidLoad()
        

          tableView.rowHeight = 30

        loadDrivers()
        getDriverTotal(nameToGet: "Wingrove V")
        title = "Driver Names & Total RDW \(totalNumberOfDrivers)"

        dataSource = setupDataSource()
        self.tableView.reloadData()

          
    }

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return people.count
    }
    
    override func viewDidAppear(_ animated: Bool) {
      super.viewWillAppear(animated)
        
        UIView.performWithoutAnimation {
            do {
                try fetchedResultsController.performFetch()
            } catch let error as NSError {
                print("Fetching error: \(error), \(error.userInfo)")
            }
        }
      

    }

    
    //---------------------------------------------------------------------------------------
//MARK: - ADD a name
    @IBAction func addName(_ sender: UIBarButtonItem) {
        let alertController = UIAlertController(title: "Add Driver", message: nil, preferredStyle: .alert)
        
        alertController.addTextField { (newDriverName) in
            newDriverName.placeholder = "Name"
        }
        alertController.addTextField(configurationHandler: { (newRDW) in
            newRDW.keyboardType = .numberPad
            newRDW.placeholder = "Starting Number of RDW"
            
        })
        let saveAction = UIAlertAction(title: "Save", style: .default) {_ in

            if alertController.textFields![0].hasText && alertController.textFields![1].hasText {
            let newDriverNameField = alertController.textFields![0]
            let newRDWField = alertController.textFields![1]
            let newRDW = Int(newRDWField.text!)
                let driverName = DriverName(context: self.coreDataStack.managedContext)
                driverName.name = newDriverNameField.text
                driverName.totalText = newRDWField.text
                driverName.total = Int32(newRDW!)
                self.coreDataStack.saveContext()
                self.totalNumberOfDrivers += 1
            self.title = "Driver Names & Total RDW \(self.totalNumberOfDrivers)"
            self.tableView.reloadData()
            } else {
                return
            }
        }

          
          let cancelAction = UIAlertAction(title: "Cancel", style: .cancel)
     
        alertController.addAction(saveAction)
        alertController.addAction(cancelAction)
          
          present(alertController, animated: true)
    }
    
    //MARK: - Load Drivers
    func loadDrivers() {
            let request : NSFetchRequest<DriverName> = DriverName.fetchRequest()
            do {
              people = try context.fetch(request)
            } catch {
            print("Error fetching data from context \(error)")
            }
        }
        
    //MARK: - Get Driver Total
    func getDriverTotal(nameToGet: String) {
        let nameFetch: NSFetchRequest<DriverName> = DriverName.fetchRequest()
        nameFetch.predicate = NSPredicate(format: "%K == %@", #keyPath(DriverName.name), nameToGet)

        var x = 0

        totalNumberOfDrivers = people.count

        while x != people.count {

          let person = people[x]
            if person.value(forKeyPath: "name") as! String == nameToGet {
                vaughansTotal = person.value(forKeyPath: "total") as! Int

            }
            x = x + 1
        }
    }

    //---------------------------------------------------------------------------------------
    
    //---------------------------------------------------------------------------------------
    //MARK: - delete a row
    
//    func tableView(_ tableView: UITableView,  canEditRowAt indexPath: IndexPath) -> Bool {
//        return true
//      }
//    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
//        if editingStyle == .delete {
//
//            guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
//                return
//            }
//            let managedContext = appDelegate.persistentContainer.viewContext
//            managedContext.delete(driverName[indexPath.row])
//            do {
//                try managedContext.save()
//            } catch {
//
//            }
//            driverName.remove(at: indexPath.row)
//           tableView.deleteRows(at: [indexPath], with: .fade)
//
//            totalNumberOfDrivers -= 1
//            title = "Driver Names & Total RDW \(totalNumberOfDrivers)"
//            self.tableView.reloadData()
//
//        } else if editingStyle == .insert {
//            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
//        }
//    }


}



// MARK: - Internal
extension ViewController {

  func setupDataSource() -> UITableViewDiffableDataSource<String, DriverName> {
    return UITableViewDiffableDataSource(tableView: tableView) { [unowned self](tableView, indexPath, driverName) -> UITableViewCell? in
      let cell = tableView.dequeueReusableCell(withIdentifier: self.driverCellIdentifier, for: indexPath)
      self.configure(cell: cell, for: driverName)
      return cell
    }
  }

  func configure(cell: UITableViewCell, for driverName: DriverName) {

    guard let cell = cell as? DriverNameCell else {
      return
    }

    if vaughansTotal < driverName.total {

        cell.detail.textColor = UIColor.red
        cell.title.text = driverName.name
        cell.detail.text = driverName.totalText
        
    } else {

        cell.detail.textColor = UIColor.black
        cell.title.text = driverName.name
        cell.detail.text = driverName.totalText
    }

  }
}



// MARK: - NSFetchedResultsControllerDelegate
extension ViewController: NSFetchedResultsControllerDelegate {

  func controller(
    _ controller: NSFetchedResultsController<NSFetchRequestResult>,
    didChangeContentWith
    snapshot: NSDiffableDataSourceSnapshotReference) {

    var diff = NSDiffableDataSourceSnapshot<String, DriverName>()
    snapshot.sectionIdentifiers.forEach { section in

      diff.appendSections([section as! String])

      let items = snapshot.itemIdentifiersInSection(withIdentifier: section)
        .map { (objectId: Any) -> DriverName in
          let oid =  objectId as! NSManagedObjectID
          return controller.managedObjectContext.object(with: oid) as! DriverName
      }

      diff.appendItems(items, toSection: section as? String)
    }

    dataSource?.apply(diff)
  }
}
4

0 回答 0