Swift n内部一致性异常';,原因:';没有-layoutAttributesForItemAtIndexPath的UICollectionViewLayoutAttributes实例,自定义布局

Swift n内部一致性异常';,原因:';没有-layoutAttributesForItemAtIndexPath的UICollectionViewLayoutAttributes实例,自定义布局,swift,uicollectionview,uicollectionviewlayout,Swift,Uicollectionview,Uicollectionviewlayout,我有一个自定义UICollectionLayout的UICollectionView。这一切都很好,直到我尝试插入一行 然后我得到了下面的错误,似乎不知道如何解决它 *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'no UICollectionViewLayoutAttributes instance for -layoutAttributesForItemAtI

我有一个自定义UICollectionLayout的UICollectionView。这一切都很好,直到我尝试插入一行

然后我得到了下面的错误,似乎不知道如何解决它

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'no UICollectionViewLayoutAttributes instance for -layoutAttributesForItemAtIndexPath: <NSIndexPath: 0xc000000000000016> {length = 2, path = 0 - 0}'
*** First throw call stack:
(
0   CoreFoundation                      0x000000010915ae65 __exceptionPreprocess + 165
1   libobjc.A.dylib                     0x0000000108789deb objc_exception_throw + 48
2   CoreFoundation                      0x000000010915acca +[NSException raise:format:arguments:] + 106
3   Foundation                          0x000000010591a4de -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 198
4   UIKit                               0x00000001073e361c -[UICollectionViewData layoutAttributesForItemAtIndexPath:] + 627
5   UIKit                               0x00000001073a2859 __51-[UICollectionView _viewAnimationsForCurrentUpdate]_block_invoke1541 + 176
6   UIKit                               0x00000001073a02ed -[UICollectionView _viewAnimationsForCurrentUpdate] + 4524
7   UIKit                               0x00000001073a4a5c __62-[UICollectionView _updateWithItems:tentativelyForReordering:]_block_invoke1611 + 197
8   UIKit                               0x0000000106be01b8 +[UIView(Animation) performWithoutAnimation:] + 65
9   UIKit                               0x00000001073a3e07 -[UICollectionView _updateWithItems:tentativelyForReordering:] + 3241
10  UIKit                               0x000000010739eb98 -[UICollectionView _endItemAnimationsWithInvalidationContext:tentativelyForReordering:] + 15556
11  UIKit                               0x00000001073a5ee7 -[UICollectionView _performBatchUpdates:completion:invalidationContext:tentativelyForReordering:] + 415
12  UIKit                               0x00000001073a5d25 -[UICollectionView _performBatchUpdates:completion:invalidationContext:] + 74
13  UIKit                               0x00000001073a5cc8 -[UICollectionView performBatchUpdates:completion:] + 53
14  Qanda                               0x0000000103d9e0d9 _TFC5Qanda32HomeFeedCollectionViewController22redrawViewAfterNewDatafS0_FGSaCS_10QandaModel_T_ + 4105
15  Qanda                               0x0000000103dad5ca _TFFFC5Qanda32HomeFeedCollectionViewController9fetchDataFS0_FT_T_U_FTGSqGSaCS_10QandaModel__Sb_T_U0_FT_T_ + 1274
16  Qanda                               0x0000000103afc6b7 _TTRXFo__dT__XFdCb__dT__ + 39
17  libdispatch.dylib                   0x0000000109dd7e5d _dispatch_call_block_and_release + 12
18  libdispatch.dylib                   0x0000000109df849b _dispatch_client_callout + 8
19  libdispatch.dylib                   0x0000000109de02af _dispatch_main_queue_callback_4CF + 1738
20  CoreFoundation                      0x00000001090bad09 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 9
21  CoreFoundation                      0x000000010907c2c9 __CFRunLoopRun + 2073
22  CoreFoundation                      0x000000010907b828 CFRunLoopRunSpecific + 488
23  GraphicsServices                    0x000000010c171ad2 GSEventRunModal + 161
24  UIKit                               0x0000000106b34610 UIApplicationMain + 171
25  Qanda                               0x0000000103bb537d main + 109
26  libdyld.dylib                       0x0000000109e2c92d start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
***由于未捕获的异常“NSInternalInconsistencyException”而终止应用程序,原因:“没有-layoutAttributesForItemAtIndexPath的UICollectionViewLayoutAttributes实例:{length=2,path=0-0}”
***第一次抛出调用堆栈:
(
0 CoreFoundation 0x000000010915ae65例外预处理+165
1 libobjc.A.dylib 0x0000000108789deb objc_异常_抛出+48
2 CoreFoundation 0x000000010915acca+[N异常提升:格式:参数:][106
3基金会0x000 000 010591A4DE-[ NSRealStutsHuffer-HooRealRuleIn方法:对象:文件:文件号:描述:] + 198
4 UIKit 0x00000001073e361c-[UICollectionViewData layoutAttributesForItemAtIndexPath:+627
5 UIKit 0x00000001073a2859 uu 51-[UICollectionView u viewAnimationsForCurrentUpdate]u block_uinvoke1541+176
6 UIKit 0x00000001073a02ed-[UICollectionView\U viewAnimationsForCurrentUpdate]+4524
7 UIKit 0x00000001073a4a5c uu 62-[UICollectionView u updateWithItems:tentiveyForreOrdering:][u block_uinvoke1611+197
8 UIKit 0x0000000106be01b8+[UIView(动画)性能无动画:+65
9 UIKit 0x00000001073a3e07-[UICollectionView\u updateWithItems:tentivelyforreOrdering:+3241
10 UIKit 0x000000010739eb98-[UICollectionView\u EndItemAnimationWithInvalizationContext:tentiveyForreOrdering:+15556
11 UIKit 0x00000001073a5ee7-[UICollectionView\u性能更新:完成:失效上下文:潜在订单:+415
12 UIKit 0x00000001073a5d25-[UICollectionView\u性能更新:完成:无效上下文:+74
13 UIKit 0x00000001073a5cc8-[UICollectionView性能更新:完成:][53
14 Qanda 0x0000000103d9e0d9\u TFC5Qanda32 HomeFeedCollectionViewController 22在新数据FS0\u FGSaCS\u 10QandaModel\u T+4105后重新绘制视图
15 Qanda 0x0000000103dad5ca\U TFFFC5Qand32 HomeFeedCollectionViewController9获取数据FS0\U FT\U FTGSqGSaCS\U 10QandaModel\U Sb\U T\U U0\U FT\U+1274
16 Qanda 0x0000000103afc6b7_TTRXFo___dT__XFdCb___dT_+39
17 libdispatch.dylib 0x0000000109dd7e5d调度调用块和释放+12
18 libdispatch.dylib 0x0000000109df849b调度客户调用+8
19 libdispatch.dylib 0x0000000109de02af调度主队列回调4CF+1738
20 CoreFoundation 0x00000001090bad09\uuu CFRUNLOOP\u正在维护\u主\u调度\u队列\uu9
21 CoreFoundation 0x000000010907c2c9\uuu CFRunLoopRun+2073
22 CoreFoundation 0x000000010907b828 CFRunLoopRunSpecific+488
23图形服务0x000000010c171ad2 GSEventRunModal+161
24 UIKit 0x0000000106b34610 UIApplicationMain+171
25 Qanda 0x0000000103bb537d干管+109
26 libdyld.dylib 0x0000000109e2c92d启动+1
)
libc++abi.dylib:以NSException类型的未捕获异常终止
以下是我的布局代码:

var numberOfColumns: Int = 1
let cellPadding: CGFloat = 10
let buttonContainerHeight: CGFloat = 50
let DEFAULT_HEIGHT: CGFloat = 80

private var contentWidth: CGFloat = UIScreen.mainScreen().bounds.width
private var totalContentHeight: CGFloat  = 0.0

// Delegate
var delegate: HomeFeedCollectionViewLayoutDelegate?


var cache = [UICollectionViewLayoutAttributes]()


override func prepareLayout() {

    // If cache is empty, calculate the layout
    if cache.isEmpty {
        // Set the size
        let columnWidth = contentWidth / CGFloat(numberOfColumns)
        var contentHeight: CGFloat  = 0.0
        var column = 0
        let xOffset: CGFloat = 0
        var yOffset: CGFloat = 0
        var yOffsetArray = [CGFloat]()

        // First check if sections actually exist
        if collectionView!.numberOfSections() > 0 {

            // Loop through items in section
            for item in 0 ..< collectionView!.numberOfItemsInSection(0) {

                let indexPath = NSIndexPath(forItem: item, inSection: 0)
                let width = columnWidth - cellPadding * 2

                let questionHeight = delegate?.collectionView(collectionView!, heightForQuestionAtIndexPath: indexPath, withWidth:width)


                // Calculate frame
                var height: CGFloat!

                if questionHeight > 0 {
                    height = DEFAULT_HEIGHT + buttonContainerHeight + questionHeight! + 10
                }
                else {
                    height = contentWidth + buttonContainerHeight
                }


                if yOffsetArray.isEmpty {
                    log.debug("yOffsetArray is EMPTY")
                }
                else {
                    yOffset = yOffsetArray[item - 1] - cellPadding
                }

                yOffsetArray.append(height + yOffset)


                let frame = CGRect(x: xOffset, y: yOffset, width: columnWidth, height: height)
                let insetFrame = CGRectInset(frame, cellPadding, cellPadding)

                // Create instance of UICollectionViewLayoutAttribute & set insetFrame
                let attributes = UICollectionViewLayoutAttributes(forCellWithIndexPath: indexPath)
                attributes.frame = insetFrame
                cache.append(attributes)

                // Make content height
                contentHeight = contentHeight + (height - cellPadding)

                column = column >= (numberOfColumns - 1) ? 0 : ++column

            }

            self.totalContentHeight = contentHeight

        }

    }

}


override func collectionViewContentSize() -> CGSize {
    return CGSize(width: UIScreen.mainScreen().bounds.width, height: self.totalContentHeight + cellPadding)
}


override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
    var layoutAttributes = [UICollectionViewLayoutAttributes]()

    for attributes in cache {
        if CGRectIntersectsRect(attributes.frame, rect) {
            layoutAttributes.append(attributes)
        }
    }
    return layoutAttributes
}
var numberOfColumns:Int=1
让cellPadding:CGFloat=10
让按钮保持高度:CGFloat=50
设默认高度:CGFloat=80
私有变量contentWidth:CGFloat=UIScreen.mainScreen().bounds.width
私有变量totalContentHeight:CGFloat=0.0
//委派
变量委托:HomeFeedCollectionViewLayoutDelegate?
变量缓存=[UICollectionViewLayoutAttribute]()
重写函数prepareLayout(){
//如果缓存为空,则计算布局
如果cache.isEmpty{
//设定大小
让columnWidth=contentWidth/CGFloat(numberOfColumns)
变量contentHeight:CGFloat=0.0
变量列=0
设xOffset:CGFloat=0
变量yOffset:CGFloat=0
var yOffsetArray=[CGFloat]()
//首先检查节是否确实存在
如果collectionView!.numberOfSections()>0{
//循环浏览第节中的项目
对于0..0{
高度=默认高度+按钮高度+问题高度!+10
}
否则{
高度=内容宽度+按钮容器高度
}
如果yOffsetArray.isEmpty{
调试(“yOffsetArray为空”)
}
否则{
yOffset=yOffsetArray[项目-1]-单元格填充
}
附加(高度+yOffset)
设frame=CGRect(x:xOffset,y:yOffset,width:columnWidth,height:height)
let insetFrame=CGRectInset(框架、单元格填充、单元格填充)
//创建UICollectionViewLayoutAttribute的实例并设置insetFrame
let attributes=UICollectionViewLayoutAttribute(forCellWithIndexPath:indexPath)
attributes.frame=insetFrame
layoutAttributesForElementsInRect = [<UICollectionViewLayoutAttributes: 0x7ffc1d8baf70> index path: (<NSIndexPath: 0xc000000000000016> {length = 2, path = 0 - 0}); frame = (10 10; 355 405); , <UICollectionViewLayoutAttributes: 0x7ffc1d8a5930> index path: (<NSIndexPath: 0xc000000000200016> {length = 2, path = 0 - 1}); frame = (10 425; 355 143.222); , <UICollectionViewLayoutAttributes: 0x7ffc1d837240> index path: (<NSIndexPath: 0xc000000000400016> {length = 2, path = 0 - 2}); frame = (10 578.222; 355 143.222); [...] <UICollectionViewLayoutAttributes: 0x7ffc1d8d02f0> index path: (<NSIndexPath: 0xc000000002600016> {length = 2, path = 0 - 19}); frame = (10 3229.44; 355 143.222); ]

 *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'no UICollectionViewLayoutAttributes instance for -layoutAttributesForItemAtIndexPath: <NSIndexPath: 0xc000000000200016> {length = 2, path = 0 - 1}'
self.collectionView?.performBatchUpdates({ () -> Void in
        // add new items into collection
        self.collectionView?.insertItemsAtIndexPaths(indexPaths)

        }, completion: { (finished) -> Void in
            // do insertion animations
    });
override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? {

    // Logic that calculates the UICollectionViewLayoutAttributes of the item
    // and returns the UICollectionViewLayoutAttributes
    return self.singleItemLayout(indexPath)
}