ios - 根据单元格选择将核心数据传递给 ViewController

标签 ios swift core-data uicollectionview

我需要在选择 UICollectionView Cell 时呈现一个新的 ViewController,并传递来自用于填充所选单元格的实体的数据。

这是用于填充单元格数据的代码:

   let pets = PersistenceManager.shared.fetch(Pet.self)
     var _fetchResultsController: NSFetchedResultsController <Pet>?
    var fetchResultsController: NSFetchedResultsController <Pet>?{
        get{
            if _fetchResultsController == nil {

                let moc = PersistenceManager.shared.context
                moc.performAndWait {
                    let fetchRequest = PersistenceManager.shared.petsFetchRequest()
                    _fetchResultsController = NSFetchedResultsController.init(fetchRequest: fetchRequest, managedObjectContext: moc, sectionNameKeyPath: nil, cacheName: nil) as? NSFetchedResultsController<Pet>
                    _fetchResultsController?.delegate = self
                    do {
                        try self._fetchResultsController?.performFetch()
                    }catch {
                    }
                }
            }
            return _fetchResultsController
        }
    }

 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionViewHorizontal.dequeueReusableCell(withReuseIdentifier: "HorCell", for: indexPath) as! PRMainHorizontalCollectionViewCell

        if let pet= self.fetchResultsController?.fetchedObjects, indexPath.row < pet.count{
            let _pet= fetchResultsController!.object(at: indexPath)
// cell UI goes here
        }
        return cell
    }

我知道我需要使用 didSelectItemAt,我只是不知道函数中需要包含哪些信息。请让我知道更好地帮助回答这个问题所需的任何其他信息。谢谢。

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

// Added the line below based on karthik's answer. But I am unsure how to implement it.
    let selectedObj = fetchResultsController!.object(at: indexPath)

    let vc = self.storyboard?.instantiateViewController(withIdentifier: "selectedPetViewController") as! PRSelectedPetViewController

    navigationController?.pushViewController(vc, animated: true)

}

最佳答案

我更喜欢以下架构:

这是带有数据的主 Controller 。 为了更好地理解,我将简化数据源。

class ViewController: UIViewController {
    // code ...

    @IBOutlet var collectionView: UICollectionView!
    fileprivate var data = [Pet]()
}

extension ViewController: UICollectionViewDataSource {
    // code ...

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return data.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "HorCell", for: indexPath) as? PRMainHorizontalCollectionViewCell else {
            return UICollectionViewCell()
        }

        let pet = data[indexPath.row]
        // TODO: configure cell using pet ...
        return cell
    }

}

extension ViewController: UICollectionViewDelegate {

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let row = indexPath.row
        let pet = data[row]

        // TODO: Get the child controller in any way convenient for you.
        let childController = ChildViewController()
        // With the help of the delegate, we will receive notification of changes pet.
        childController.delegate = self

        // Thus, we pass the data to the child controller.
        childController.pet = pet
        childController.indexPath = indexPath

        // TODO: Present the view controller in any way convinient for you.
    }

}

extension ViewController: ChildViewControllerDelegate {

    func saveButtonPressed(_ controller: ChildViewController) {
        guard let pet = controller.pet, let indexPath = controller.indexPath else {
            return
        }

        // We save data and reload the cell whose data we changed.
        self.data[indexPath.row] = pet
        collectionView.reloadItems(at: [indexPath])
    }

    func cancelButtonPressed(_ controller: ChildViewController) {
        // Do something if necessary...
    }

}

除了 Controller 之外,子 Controller 还提供了用于通知更改的委托(delegate)协议(protocol)。

protocol ChildViewControllerDelegate {

    func saveButtonPressed(_ controller: ChildViewController)

    func cancelButtonPressed(_ controller: ChildViewController)

}

// This is the controller you want to show after selecting a cell.
// I assume that in the child controller there is a button to save and cancel.
class ChildViewController: UIViewController {

    var delegate: ChildViewControllerDelegate?

    // The object whose data we are editing in the controller.
    var pet: Pet!

    // The location of the object in the main controller.
    var indexPath: IndexPath!

    override func viewDidLoad() {
        // TODO: Configure user interface using self.pet
    }

    @IBAction func saveButtonPressed(_ button: UIButton) {
        delegate?.saveButtonPressed(self)
    }

    @IBAction func cancelButtonPressed(_ button: UIButton) {
        delegate?.cancelButtonPressed(self)
    }

}

关于ios - 根据单元格选择将核心数据传递给 ViewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54637714/

相关文章:

ios - 填充 TableView 中的 JSON 数组和 CoreData

ios - swift EXC_BAD_INSTRUCTION

ios - 布局问题,自动布局已启用但似乎不起作用

ios - 如何正确使用 setNeedsDisplay()

swift 4 : Image inside UIView only display after second UIViewController call

ios - 核心数据获取请求关系属性谓词

ios - 在 iOS 中将通知从模型发送到 Controller

ios - 变色龙框架与 Swift 4 不兼容?

swift - 如何将 NSArray<NSInteger> 或 NSData 转换为 UnsafeMutablePointer<UInt8> 并返回 Swift?

ios - 获取与自身具有多对多链接的链接实体?