NSInternalInconsistencyException',原因:'-layoutAttributesForItemAtIndexPath 没有 UICollectionViewLayoutAttributes 实例,自定义布局

2024-01-26

我有一个带有自定义 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

这是我的布局的代码:

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
}

EDIT:缩小错误的根源,似乎只有首先重新加载 CV 时,返回的 UICollectionViewLayoutAttributes 才会更新为正确的新值。但是,如果我这样做,批量更新会抛出一个错误,指出之后的总行数应等于之前加上插入的行数……这是有道理的。

EDIT 2: 现在我很茫然。批量更新是否尝试从默认布局而不是我的自定义布局中检索布局?

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
    });

the layoutAttributesForElementsInRect方法未被调用并且layoutAttributesForItemAtIndexPath被调用。

因此,您还必须覆盖layoutAttributesForItemAtIndexPath在自定义布局中,如下所示:

override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? {

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

编辑:此外,如果批处理时遇到闪烁insertItemsAtIndexPaths自己的方法。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

NSInternalInconsistencyException',原因:'-layoutAttributesForItemAtIndexPath 没有 UICollectionViewLayoutAttributes 实例,自定义布局 的相关文章

  • iOS 11.x 系统颜色

    我读过很多关于如何自定义视图颜色的文章 但没有任何关于检索标准控件 如 iOS 11 x 或以前版本中的导航栏 状态栏和选项卡栏 的系统颜色的文章 UIColor 类有 3 种系统颜色 但它们几乎没有用 例如 调用 UINavigation
  • 查询链接到 GeoFire 的 firebase 数据

    读完这些问题后 将 Geofire 位置与 Firebase 条目关联 https stackoverflow com questions 33885733 associate geofire location with firebase
  • 无法识别的选择器发送到类

    我已经看到 这是一个常见问题 但我自己找不到任何解决方案 这是代码 class ButtonViewController UIViewController override func viewDidLoad super viewDidLoa
  • Xcode 调试器显示错误的变量值

    我之前问过类似的问题here https stackoverflow com q 53092448 1187415 这个版本有更简单的例子 更新摘要 Xcode 在调试器变量部分中为每个字符串显示 FAIL Swift print 语句显示
  • swift 中 pch 的替代品是什么?

    我想知道可以用什么来代替 swift 中的 pch 有没有 pch 的替代方案或方法可以快速摆脱导入 这样我们就不需要对所有类都这样做 我不想一直随身携带 进口 swift 中 pch 的最佳替代品是什么 您无法在 swift 中定义 宏
  • 如何将一个 SwiftUI View 作为变量传递给另一个 View 结构

    我正在实施一个very自定义 NavigationLink 称为MenuItem并希望在整个项目中重用它 它是一个符合以下条件的结构体View并实施var body some View其中包含一个NavigationLink 我需要以某种方
  • Xcode 8:使用 iOS 9.3 基础 SDK 编译?

    我在 Xcode 8 0 beta 8S128d 中将 iOS 应用程序升级到 Swift 3 0 我以为一切都已准备就绪 并将其上传到 iTunes Connect 当我点击 提交审核 时 它给了我一个包含 26 个错误的列表 每个嵌入式
  • 在 swift ios 中播放远程 mp3 文件需要花费大量时间

    我有麻烦了 我想在我的应用程序中播放远程 mp3 文件 但 mp3 文件需要很长时间 大约 5 6 分钟 来播放 为什么 任何人都可以建议我应该做什么 import UIKit import AVFoundation class TestV
  • 在 Pages 文稿中打开文本—Swift

    在我的 Swift 2 应用程序中 用户通过文本字段创建一串文本 然后将其共享给另一个应用程序 现在 我只能将文本共享为 txt 文件 这不提供选项Open In Pages当我打开系统共享对话框时 如何才能让用户可以选择将输入的文本作为
  • Swift 语言中的 #ifdef 替换

    在 C C Objective C 中 您可以使用编译器预处理器定义宏 此外 您可以使用编译器预处理器包含 排除代码的某些部分 ifdef DEBUG Debug only code endif Swift 中有类似的解决方案吗 是的 你可
  • Swift:Tableview 在导航栏下方滚动但在状态栏上方滚动?

    我使用以下技巧隐藏了导航栏的阴影 self navigationController navigationBar setBackgroundImage UIImage for default self navigationControlle
  • 上下文菜单未在 SwiftUI 中更新

    我正在尝试设置 SwiftUI contextMenu带有一个切换按钮Bool价值 上下文菜单的按钮文本应该在以下情况下更改 Bool切换 但上下文菜单不会更新 有没有办法强制更新上下文菜单 描述问题的示例代码 import SwiftUI
  • 无法在 xcode 8 beta 6 上编译 AWS CustomIdentityProvider

    我在 iOS 应用程序中使用 Amazon Cognito 和 Facebook 登录 直到 beta 5 为止此代码从这个SO线程 https stackoverflow com questions 37597388 aws cognit
  • 从字典创建 Swift 对象

    如何根据 Swift 字典中的查找值动态实例化类型 希望这对其他人有用 我们需要进行一些研究才能弄清楚这一点 目标是避免巨大的 if 或 switch 语句从值创建每个对象类型的反模式 class NamedItem CustomStrin
  • Swift PageControl 当前页面上更大的点

    我试图将当前页面的点缩放为大于未 选择 的点 我正在使用滚动视图委托来确定哪个页面是当前的 目前 点的大小没有变化 我将如何实现这一目标 func scrollViewDidEndDecelerating scrollView UIScro
  • Swift 中通过可选绑定进行安全(边界检查)数组查找?

    如果我在 Swift 中有一个数组 并尝试访问超出范围的索引 则会出现一个不足为奇的运行时错误 var str Apple Banana Coconut str 0 Apple str 3 EXC BAD INSTRUCTION 但是 我会
  • Swift 单元测试 - 如何断言 CGColor 是它应该的样子?

    使用 Xcode V7 2 尝试进行单元测试 需要验证是否已设置正确的颜色 并收到以下消息 Cannot invoke XCTAssertEqual with an argument list of type CGColor CGColor
  • 自动生成的 Swift 桥接标头中“找不到接口声明”

    我当前的项目包含 Swift 和 Objective C 代码 两种类型的源文件都使用另一种语言的代码 当我进行完全清理并重新编译时 几乎每个 Swift 类声明都出现错误Module Swift h 形式为 Cannot find int
  • TestFlight 安装的应用程序因 Swift 包管理器依赖项而崩溃

    我们已经迁移了一些 CocoaPod 依赖项 以便在 Xcode 11 中使用 Swift Package Manager 进行构建和链接 但是 每当我们将应用程序提交到 AppStore Connect 并使用 TestFlight 进行
  • 从 URL 解析 JSON 最终出现错误 - Swift 5

    我正在尝试用 swift 编写一个函数 从 URL JSON 获取数据 并将其分配给 swift 中的变量 这是函数 func getBikeData guard let url URL string https api citybik e

随机推荐