【问题标题】:cellForItemAtIndexPath not being called, unclear as to whycellForItemAtIndexPath 没有被调用,不清楚为什么
【发布时间】:2016-06-16 23:34:35
【问题描述】:

我已经阅读了一些其他问题,这些问题与 CollectionView 的大小有关。我已经尝试按照这些答案中的建议调整大小,但它们都不起作用。我正在使用一个 NSFetchedResultsController ,它也为我复杂(我想知道它是否与它不触发有关)。

无论如何,真正的问题是我的 UICollectionView 没有内容出现。运行时没有错误,只是一个空白屏幕。我正在使用 Swift(显然)。

这是我在 ViewController 中的代码:

import UIKit
import CoreData

private let reuseIdentifier = "Family"
private var selectedFirstName:String = "Blank"
private var selectedLastName:String = "Blank"
private var selectedNumber:String = "Blank"
private var selectedEmail:String = "Blank"

class FamilyViewController: UIViewController, UICollectionViewDataSource {

var coreDataStack: CoreDataStack!
var fetchedResultsController: NSFetchedResultsController!

@IBOutlet var familyCollectionView: UICollectionView!

override func viewDidLoad() {
    super.viewDidLoad()

    //1
    let fetchRequest = NSFetchRequest(entityName: "Family")

    let firstNameSort =
    NSSortDescriptor(key: "firstName", ascending: true)

    fetchRequest.sortDescriptors = [firstNameSort]

    //2
    self.coreDataStack = CoreDataStack() 
    fetchedResultsController =
        NSFetchedResultsController(fetchRequest: fetchRequest,
            managedObjectContext: coreDataStack.context,
            sectionNameKeyPath: nil,
            cacheName: nil)

    fetchedResultsController.delegate = CollectionViewFetchedResultsControllerDelegate(collectionView: familyCollectionView)

    //3
    do {
        try fetchedResultsController.performFetch()
    } catch let error as NSError {
        print("Error: \(error.localizedDescription)")
    }
}


func configureCell(cell: FamilyCCell, indexPath: NSIndexPath) { let family = fetchedResultsController.objectAtIndexPath(indexPath) as! Family

    cell.firstNameLabel.text = family.firstName
    print("configureCell ran")

}


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

func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    print("numberOfSectionsInCollectionView ran")
    return fetchedResultsController.sections!.count
}


func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of items
    let sectionInfo = fetchedResultsController.sections![section]
    print("numberOfItemsInSection ran")
    return sectionInfo.numberOfObjects
}


func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! FamilyCCell

    print("cellForItemAtIndexPath ran")
    configureCell(cell, indexPath: indexPath)

    return cell
}




override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if (segue.identifier == "showDetail") {
        let detailVC = segue.destinationViewController as! ContactViewController

        print("prepareForSegue ran")
        detailVC.detailFirstName = selectedFirstName
        detailVC.detailLastName = selectedLastName
        detailVC.detailNumber = selectedNumber
        detailVC.detailEmail = selectedEmail
    }
}
}

extension FamilyViewController: UICollectionViewDelegate {

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    print("didSelectItemAtIndexPath ran")
    collectionView.delegate = self

    let family = fetchedResultsController.objectAtIndexPath(indexPath) as! Family

    selectedFirstName = family.firstName!
    selectedLastName = family.lastName!
    selectedNumber = family.phone!
    selectedEmail = family.email!
    coreDataStack.saveContext()
}
}


class CollectionViewFetchedResultsControllerDelegate: NSObject, NSFetchedResultsControllerDelegate {

// MARK: Properties

private let collectionView: UICollectionView
private var blockOperations: [NSBlockOperation] = []

// MARK: Init

init(collectionView: UICollectionView) {
    self.collectionView = collectionView
}

// MARK: Deinit

deinit {
    blockOperations.forEach { $0.cancel() }
    blockOperations.removeAll(keepCapacity: false)
}

// MARK: NSFetchedResultsControllerDelegate

func controllerWillChangeContent(controller: NSFetchedResultsController) {
    blockOperations.removeAll(keepCapacity: false)
}

func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {

    switch type {

    case .Insert:
        guard let newIndexPath = newIndexPath else { return }
        let op = NSBlockOperation { [weak self] in self?.collectionView.insertItemsAtIndexPaths([newIndexPath]) }
        blockOperations.append(op)

    case .Update:
        guard let newIndexPath = newIndexPath else { return }
        let op = NSBlockOperation { [weak self] in self?.collectionView.reloadItemsAtIndexPaths([newIndexPath]) }
        blockOperations.append(op)

    case .Move:
        guard let indexPath = indexPath else { return }
        guard let newIndexPath = newIndexPath else { return }
        let op = NSBlockOperation { [weak self] in self?.collectionView.moveItemAtIndexPath(indexPath, toIndexPath: newIndexPath) }
        blockOperations.append(op)

    case .Delete:
        guard let indexPath = indexPath else { return }
        let op = NSBlockOperation { [weak self] in self?.collectionView.deleteItemsAtIndexPaths([indexPath]) }
        blockOperations.append(op)

    }
}

func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) {

    switch type {

    case .Insert:
        let op = NSBlockOperation { [weak self] in self?.collectionView.insertSections(NSIndexSet(index: sectionIndex)) }
        blockOperations.append(op)

    case .Update:
        let op = NSBlockOperation { [weak self] in self?.collectionView.reloadSections(NSIndexSet(index: sectionIndex)) }
        blockOperations.append(op)

    case .Delete:
        let op = NSBlockOperation { [weak self] in self?.collectionView.deleteSections(NSIndexSet(index: sectionIndex)) }
        blockOperations.append(op)

    default: break

    }
}

func controllerDidChangeContent(controller: NSFetchedResultsController) {
    collectionView.performBatchUpdates({
        self.blockOperations.forEach { $0.start() }
        }, completion: { finished in
            self.blockOperations.removeAll(keepCapacity: false)
    })
}
}

我有打印语句确认 cellForItemAtIndexPath 没有运行。有任何想法吗?我意识到这是非常具体的,我给出了一大堆代码,只是不太确定错误可能来自哪里。感谢您提前提供任何帮助。

【问题讨论】:

  • 我相信我已经做到了。我在情节提要中控制单击它们并将collectionView 连接到Datasource/Delegate。我需要在那里连接视图控制器代码的任何内容?我不这么认为,但我肯定弄错了。
  • 您是否返回非零数量的部分和项目?
  • 我正在查询 NSFetchedResultsController 的节数,所以它应该返回一个非零数字。
  • 我开始怀疑它是否与我与 CoreData 建立的连接有关。如果我发现任何东西,我将研究下一点并返回此处添加信息。

标签: ios swift core-data uicollectionview


【解决方案1】:

确保...您确认 UICollectionViewDelegate 协议方法。
设置collectionview.delegate = self
collectionview.datasource = self

【讨论】:

  • 虽然通常是这样,但它并没有修复此代码。我已经把它们连接起来了。
  • 只是为了向以后阅读本文的人澄清,我将代码更改为不引用“CoreDataStack”。相反,我只是在这个 viewController 中创建了一个 NSObject 变量,并且能够让它以这种方式工作。我通常接受这个答案,这将是问题(委托/数据源未连接)。
【解决方案2】:

numberOfSectionsInCollectionView 方法的集合视图数据源中返回 1,在 collectionViewNumberOfCellsForSection 中返回要显示的单元格数

为了澄清 tableview 或集合视图,“部分”是一组相关的东西,其中一个单元格(或 tableview 的行)是您想要显示的实际内容 - 当您不覆盖所需的单元格数量时它将为所有部分返回 0

(早上检查确切的方法签名,如果它们稍微偏离,请编辑)

【讨论】:

    【解决方案3】:

    写下来:

    class FamilyViewController: UIViewController, UICollectionViewDataSource,UICollectionViewDelegate{ 
    

    并在您的 viewDidLoad 方法中写下这两行:

    familyCollectionView.delegate = self
    

    familyCollectionView.datasource = self
    

    【讨论】:

      猜你喜欢
      • 2020-09-09
      • 1970-01-01
      • 2013-01-18
      • 1970-01-01
      • 1970-01-01
      • 2021-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多