菜鸟教程小白 发表于 2022-12-11 18:31:14

ios - 自定义 Collection View 布局崩溃


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

<p>不幸的是,我遇到了一个问题。滚动时我遇到了崩溃:</p>

<blockquote>
<p>*** Terminating app due to uncaught exception &#39;NSInternalInconsistencyException&#39;, reason: &#39;no
UICollectionViewLayoutAttributes instance for
-layoutAttributesForItemAtIndexPath:
</p></blockquote>

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

<p>整个项目是<a href="https://github.com/ASPetrov/Grid" rel="noreferrer noopener nofollow">here</a> .然而最重要的是布局,所以为了方便,这里是:</p>

<pre><code>class GridViewLayout: UICollectionViewLayout {

    //MARK: - Setup

    private var isInitialized: Bool = false

    //MARK: - Attributes

    var attributesList: [] = []

    //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 &gt; 0 {
            for section in 0..&lt;rowsCount {
                for index in 0..&lt;columnsCount {
                  if section != 0 &amp;&amp; index != 0 {
                        continue
                  }

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

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

                  if includesRowHeader &amp;&amp; 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..&lt;rowsCount {
            var sectionAttributes: = []
            for index in 0..&lt;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 &amp;&amp; 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 &amp;&amp; section == 0 {
                  var frame = attributes.frame
                  frame.origin.y = collectionView!.contentOffset.y
                  attributes.frame = frame
                }

                if includesRowHeader &amp;&amp; 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 &gt; 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) -&gt; UICollectionViewLayoutAttributes? {
      var curLayoutAttribute: UICollectionViewLayoutAttributes? = nil

      if indexPath.section &lt; self.attributesList.count {
            let sectionAttributes = self.attributesList

            if indexPath.row &lt; sectionAttributes.count {
                curLayoutAttribute = sectionAttributes
            }
      }

      return curLayoutAttribute
    }

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

            attributes.append(contentsOf: filteredArray)
      }

      return attributes
    }

    override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -&gt; Bool {
      return true
    }

    //MARK: - Moving

    override func layoutAttributesForInteractivelyMovingItem(at indexPath: IndexPath,
                                                             withTargetPosition position: CGPoint) -&gt; 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: ,
                                    withTargetPosition targetPosition: CGPoint,
                                    previousIndexPaths: ,
                                    previousPosition: CGPoint) -&gt; UICollectionViewLayoutInvalidationContext {
      let context =super.invalidationContext(forInteractivelyMovingItems: targetIndexPaths,
                                                 withTargetPosition: targetPosition,
                                                 previousIndexPaths: previousIndexPaths,
                                                 previousPosition: previousPosition)

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

      return context
    }

}
</code></pre></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>实现 <code>layoutAttributesForItemAtIndexPath</code>。根据文档,“子类必须覆盖此方法并使用它来返回 Collection View 中项目的布局信息。”。 </p>

<p>根据我的经验,在模拟器中运行时通常不会调用此方法,但可以在设备上调用。 YMMV。</p></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 自定义 Collection View 布局崩溃,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/41520571/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/41520571/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 自定义 Collection View 布局崩溃