【发布时间】:2017-01-13 06:21:31
【问题描述】:
尝试在我的UICollecitonView 末尾添加一个“添加新”按钮。
与CoreData 合作。
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CollectionCell
configureCell(cell: cell, indexPath: indexPath)
var numberOfItems = self.collectionView(self.collectionView, numberOfItemsInSection: 0)
if (indexPath.row == numberOfItems - 1) {
var addCellButton = UIButton(frame: cell.frame)
addCellButton.setTitle("Add", for: UIControlState.normal)
cell.addSubview(addCellButton)
}
return cell
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if let sections = controller.sections {
let sectionInfo = sections[section]
return sectionInfo.numberOfObjects + 1
}
return 0
}
错误:“NSInvalidArgumentException”,原因:“索引 0 部分中索引 3 处没有对象”
我需要检查NSFetchedResultsController 的边界吗?
如此处提议:Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'no object at index 3 in section at index 0'
【问题讨论】:
-
请注意:在
cellForItemAt中,您(大部分)总是一次又一次地添加addCellButton,因为单元格被重复使用......您应该在一个单元格中只执行一次。以后你可以隐藏它,或者你应该删除它。 -
你在哪一行得到错误?
-
@muescha 我在 AppDelegate 类中遇到一般错误:UIResponder, UIApplicationDelegate ... 尝试使用打印并了解有关错误的更多信息,但不知道在哪里以及如何。
-
@muescha 关于按钮 - 我希望按钮始终位于 CollectionView 的末尾,所以我认为,每次都需要创建它,不是吗?
-
没有。单元格被重复使用。所以重用的单元格仍然有之前使用时添加的 Button。您可以在 3d 调试视图中检查这一点。您只看到一个按钮,因为其他按钮就在添加的新按钮下方