草庐IT

ios - 自定义 Collection View 布局崩溃

coder 2024-01-29 原文

我已经创建了一个自定义数据网格。它基于具有自定义布局的 Collection View 。布局修改了第一个部分和行属性,使它们具有粘性,因此当用户滚动时,其他行和部分应该位于粘性下方。这个布局的想法不是我的,我只是采用了它。 (我不能将功劳归于真正的创作者,在我的研究中,我发现了如此多的布局变体,以至于我不确定哪个是原始布局)。

不幸的是,我遇到了一个问题。滚动时发生崩溃:

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'no UICollectionViewLayoutAttributes instance for -layoutAttributesForItemAtIndexPath:

尽管有消息,但我认为真正的问题出在 layoutAttributesForElements 方法中。我读过一些有类似问题的线程,但唯一可行的解​​决方案是返回所有缓存的属性,无论传递的矩形是什么。我只是不喜欢这样快速而肮脏的解决方案。如果您能给我任何想法/解决方案,我将不胜感激。

整个项目是here .然而,最重要的是布局,为了方便起见,这里是:

class GridViewLayout: UICollectionViewLayout {

    //MARK: - Setup

    private var isInitialized: Bool = false

    //MARK: - Attributes

    var attributesList: [[UICollectionViewLayoutAttributes]] = []

    //MARK: - Size

    private static let defaultGridViewItemHeight: CGFloat = 47
    private static let defaultGridViewItemWidth: CGFloat = 160

    static let defaultGridViewRowHeaderWidth: CGFloat = 200
    static let defaultGridViewColumnHeaderHeight: CGFloat = 80

    static let defaultGridViewItemSize: CGSize =
        CGSize(width: defaultGridViewItemWidth, height: defaultGridViewItemHeight)

    // This is regular cell size
    var itemSize: CGSize = defaultGridViewItemSize

    // Row Header Size
    var rowHeaderSize: CGSize =
        CGSize(width: defaultGridViewRowHeaderWidth, height: defaultGridViewItemHeight)

    // Column Header Size
    var columnHeaderSize: CGSize =
        CGSize(width: defaultGridViewItemWidth, height: defaultGridViewColumnHeaderHeight)

    var contentSize : CGSize!

    //MARK: - Layout

    private var columnsCount: Int = 0
    private var rowsCount: Int = 0

    private var includesRowHeader: Bool = false
    private var includesColumnHeader: Bool = false

    override func prepare() {
        super.prepare()

        rowsCount = collectionView!.numberOfSections
        if rowsCount == 0 { return }
        columnsCount = collectionView!.numberOfItems(inSection: 0)

        // make header row and header column sticky if needed
        if self.attributesList.count > 0 {
            for section in 0..<rowsCount {
                for index in 0..<columnsCount {
                    if section != 0 && index != 0 {
                        continue
                    }

                    let attributes : UICollectionViewLayoutAttributes =
                        layoutAttributesForItem(at: IndexPath(forRow: section, inColumn: index))!

                    if includesColumnHeader && section == 0 {
                        var frame = attributes.frame
                        frame.origin.y = collectionView!.contentOffset.y
                        attributes.frame = frame
                    }

                    if includesRowHeader && index == 0 {
                        var frame = attributes.frame
                        frame.origin.x = collectionView!.contentOffset.x
                        attributes.frame = frame
                    }
                }
            }

            return // no need for futher calculations
        }

        // Read once from delegate
        if !isInitialized {
            if let delegate = collectionView!.delegate as? UICollectionViewDelegateGridLayout {

                // Calculate Item Sizes
                let indexPath = IndexPath(forRow: 0, inColumn: 0)
                let _itemSize = delegate.collectionView(collectionView!,
                                                        layout: self,
                                                        sizeForItemAt: indexPath)

                let width = delegate.rowHeaderWidth(in: collectionView!,
                                                    layout: self)
                let _rowHeaderSize = CGSize(width: width, height: _itemSize.height)

                let height = delegate.columnHeaderHeight(in: collectionView!,
                                                         layout: self)
                let _columnHeaderSize = CGSize(width: _itemSize.width, height: height)

                if !__CGSizeEqualToSize(_itemSize, itemSize) {
                    itemSize = _itemSize
                }

                if !__CGSizeEqualToSize(_rowHeaderSize, rowHeaderSize) {
                    rowHeaderSize = _rowHeaderSize
                }

                if !__CGSizeEqualToSize(_columnHeaderSize, columnHeaderSize) {
                    columnHeaderSize = _columnHeaderSize
                }

                // Should enable sticky row and column headers
                includesRowHeader = delegate.shouldIncludeHeaderRow(in: collectionView!)
                includesColumnHeader = delegate.shouldIncludeHeaderColumn(in: collectionView!)
            }

            isInitialized = true
        }

        var column = 0
        var xOffset : CGFloat = 0
        var yOffset : CGFloat = 0
        var contentWidth : CGFloat = 0
        var contentHeight : CGFloat = 0

        for section in 0..<rowsCount {
            var sectionAttributes: [UICollectionViewLayoutAttributes] = []
            for index in 0..<columnsCount {
                var _itemSize: CGSize = .zero

                switch (section, index) {
                case (0, 0):
                    switch (includesRowHeader, includesColumnHeader) {
                    case (true, true):
                        _itemSize = CGSize(width: rowHeaderSize.width, height: columnHeaderSize.height)
                    case (false, true): _itemSize = columnHeaderSize
                    case (true, false): _itemSize = rowHeaderSize
                    default: _itemSize = itemSize
                    }
                case (0, _):
                    if includesColumnHeader {
                        _itemSize = columnHeaderSize
                    } else {
                        _itemSize = itemSize
                    }

                case (_, 0):
                    if includesRowHeader {
                        _itemSize = rowHeaderSize
                    } else {
                        _itemSize = itemSize
                    }
                default: _itemSize = itemSize
                }

                let indexPath = IndexPath(forRow: section, inColumn: index)
                let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)

                attributes.frame = CGRect(x: xOffset,
                                          y: yOffset,
                                          width: _itemSize.width,
                                          height: _itemSize.height).integral

                // allow others cells to go under
                if section == 0 && index == 0 { // top-left cell
                    attributes.zIndex = 1024
                } else if section == 0 || index == 0 {
                    attributes.zIndex = 1023 // any ohter header cell
                }

                // sticky part - probably just in case here
                if includesColumnHeader && section == 0 {
                    var frame = attributes.frame
                    frame.origin.y = collectionView!.contentOffset.y
                    attributes.frame = frame
                }

                if includesRowHeader && index == 0 {
                    var frame = attributes.frame
                    frame.origin.x = collectionView!.contentOffset.x
                    attributes.frame = frame
                }

                sectionAttributes.append(attributes)

                xOffset += _itemSize.width
                column += 1

                if column == columnsCount {
                    if xOffset > contentWidth {
                        contentWidth = xOffset
                    }

                    column = 0
                    xOffset = 0
                    yOffset += _itemSize.height
                }
            }

            attributesList.append(sectionAttributes)
        }

        let attributes = self.attributesList.last!.last!

        contentHeight = attributes.frame.origin.y + attributes.frame.size.height
        self.contentSize = CGSize(width: contentWidth,
                                  height: contentHeight)

    }

    override var collectionViewContentSize: CGSize {
        return self.contentSize
    }

    override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
        var curLayoutAttribute: UICollectionViewLayoutAttributes? = nil

        if indexPath.section < self.attributesList.count {
            let sectionAttributes = self.attributesList[indexPath.section]

            if indexPath.row < sectionAttributes.count {
                curLayoutAttribute = sectionAttributes[indexPath.row]
            }
        }

        return curLayoutAttribute
    }

    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        var attributes: [UICollectionViewLayoutAttributes] = []
        for section in self.attributesList {
            let filteredArray  =  section.filter({ (evaluatedObject) -> Bool in
                return rect.intersects(evaluatedObject.frame)
            })

            attributes.append(contentsOf: filteredArray)
        }

        return attributes
    }

    override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
        return true
    }

    //MARK: - Moving

    override func layoutAttributesForInteractivelyMovingItem(at indexPath: IndexPath,
                                                             withTargetPosition position: CGPoint) -> UICollectionViewLayoutAttributes {
        guard let dest = super.layoutAttributesForItem(at: indexPath as IndexPath)?.copy() as? UICollectionViewLayoutAttributes else { return UICollectionViewLayoutAttributes() }

        dest.transform = CGAffineTransform(scaleX: 1.4, y: 1.4)
        dest.alpha = 0.8
        dest.center = position

        return dest
    }

    override func invalidationContext(forInteractivelyMovingItems targetIndexPaths: [IndexPath],
                                      withTargetPosition targetPosition: CGPoint,
                                      previousIndexPaths: [IndexPath],
                                      previousPosition: CGPoint) -> UICollectionViewLayoutInvalidationContext {
        let context =  super.invalidationContext(forInteractivelyMovingItems: targetIndexPaths,
                                                 withTargetPosition: targetPosition,
                                                 previousIndexPaths: previousIndexPaths,
                                                 previousPosition: previousPosition)

        collectionView!.dataSource?.collectionView?(collectionView!,
                                                    moveItemAt: previousIndexPaths[0],
                                                    to: targetIndexPaths[0])

        return context
    }

} 

最佳答案

实现 layoutAttributesForItemAtIndexPath。根据文档,“子类必须覆盖此方法并使用它来返回 Collection View 中项目的布局信息。”。

根据我的经验,在模拟器中运行时通常不会调用此方法,但可以在设备上调用。 YMMV.

关于ios - 自定义 Collection View 布局崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41520571/

有关ios - 自定义 Collection View 布局崩溃的更多相关文章

  1. ruby - Facter::Util::Uptime:Module 的未定义方法 get_uptime (NoMethodError) - 2

    我正在尝试设置一个puppet节点,但ruby​​gems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由ruby​​gems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby

  2. ruby - 检查 "command"的输出应该包含 NilClass 的意外崩溃 - 2

    为了将Cucumber用于命令行脚本,我按照提供的说明安装了arubagem。它在我的Gemfile中,我可以验证是否安装了正确的版本并且我已经包含了require'aruba/cucumber'在'features/env.rb'中为了确保它能正常工作,我写了以下场景:@announceScenario:Testingcucumber/arubaGivenablankslateThentheoutputfrom"ls-la"shouldcontain"drw"假设事情应该失败。它确实失败了,但失败的原因是错误的:@announceScenario:Testingcucumber/ar

  3. ruby-on-rails - Rails 3.2.1 中 ActionMailer 中的未定义方法 'default_content_type=' - 2

    我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer

  4. ruby-on-rails - form_for 中不在模型中的自定义字段 - 2

    我想向我的Controller传递一个参数,它是一个简单的复选框,但我不知道如何在模型的form_for中引入它,这是我的观点:{:id=>'go_finance'}do|f|%>Transferirde:para:Entrada:"input",:placeholder=>"Quantofoiganho?"%>Saída:"output",:placeholder=>"Quantofoigasto?"%>Nota:我想做一个额外的复选框,但我该怎么做,模型中没有一个对象,而是一个要检查的对象,以便在Controller中创建一个ifelse,如果没有检查,请帮助我,非常感谢,谢谢

  5. ruby - 主要 :Object when running build from sublime 的未定义方法 `require_relative' - 2

    我已经从我的命令行中获得了一切,所以我可以运行rubymyfile并且它可以正常工作。但是当我尝试从sublime中运行它时,我得到了undefinedmethod`require_relative'formain:Object有人知道我的sublime设置中缺少什么吗?我正在使用OSX并安装了rvm。 最佳答案 或者,您可以只使用“require”,它应该可以正常工作。我认为“require_relative”仅适用于ruby​​1.9+ 关于ruby-主要:Objectwhenrun

  6. Ruby Readline 在向上箭头上使控制台崩溃 - 2

    当我在Rails控制台中按向上或向左箭头时,出现此错误:irb(main):001:0>/Users/me/.rvm/gems/ruby-2.0.0-p247/gems/rb-readline-0.4.2/lib/rbreadline.rb:4269:in`blockin_rl_dispatch_subseq':invalidbytesequenceinUTF-8(ArgumentError)我使用rvm来管理我的ruby​​安装。我正在使用=>ruby-2.0.0-p247[x86_64]我使用bundle来管理我的gem,并且我有rb-readline(0.4.2)(人们推荐的最少

  7. ruby - 在 Ruby 中有条件地定义函数 - 2

    我有一些代码在几个不同的位置之一运行:作为具有调试输出的命令行工具,作为不接受任何输出的更大程序的一部分,以及在Rails环境中。有时我需要根据代码的位置对代码进行细微的更改,我意识到以下样式似乎可行:print"Testingnestedfunctionsdefined\n"CLI=trueifCLIdeftest_printprint"CommandLineVersion\n"endelsedeftest_printprint"ReleaseVersion\n"endendtest_print()这导致:TestingnestedfunctionsdefinedCommandLin

  8. ruby - 定义方法参数的条件 - 2

    我有一个只接受一个参数的方法:defmy_method(number)end如果使用number调用方法,我该如何引发错误??通常,我如何定义方法参数的条件?比如我想在调用的时候报错:my_method(1) 最佳答案 您可以添加guard在函数的开头,如果参数无效则引发异常。例如:defmy_method(number)failArgumentError,"Inputshouldbegreaterthanorequalto2"ifnumbereputse.messageend#=>Inputshouldbegreaterthano

  9. ruby - 如何验证 IO.copy_stream 是否成功 - 2

    这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下

  10. ruby - 如何在 Grape 中定义哈希数组? - 2

    我使用Ember作为我的前端和GrapeAPI来为我的API提供服务。前端发送类似:{"service"=>{"name"=>"Name","duration"=>"30","user"=>nil,"organization"=>"org","category"=>nil,"description"=>"description","disabled"=>true,"color"=>nil,"availabilities"=>[{"day"=>"Saturday","enabled"=>false,"timeSlots"=>[{"startAt"=>"09:00AM","endAt"=>

随机推荐