集合视图布局自身大小不起作用

Collection View Layout self size not working

我的自定义集合单元格包含 WKWebView。我想使单元格高度自动适应我 WKWebView 的大小。但是我所有尝试打开自动调整单元格的尝试都失败了:(

在我的控制器中我这样做:

var p = self.htmlNotificationsCollectionView.collectionViewLayout as? NSCollectionViewFlowLayout
p?.estimatedItemSize = CGSize(width: self.htmlNotificationsCollectionView.frame.width, height: 120)

作为文档编写然后应该触发 preferredLayoutAttributesFitting 方法:

class HTMLNotificationCollectionViewItem: NSCollectionViewItem, WKNavigationDelegate {
    override func preferredLayoutAttributesFitting(_ layoutAttributes: NSCollectionViewLayoutAttributes) -> NSCollectionViewLayoutAttributes {
        print("got it")
    }
}

但没有任何效果,方法没有调用,我的单元格有固定高度 = 120

我也试过:

class HorizontallyFlushCollectionViewFlowLayout: NSCollectionViewFlowLayout {

    override func layoutAttributesForItem(at indexPath: IndexPath) -> NSCollectionViewLayoutAttributes? {
        let attributes = super.layoutAttributesForItem(at: indexPath)?.copy() as? NSCollectionViewLayoutAttributes
        guard let collectionView = collectionView else { return attributes }
        attributes?.frame.size.width = collectionView.frame.width - sectionInset.left - sectionInset.right
        return attributes

    }

    override func layoutAttributesForElements(in rect: CGRect) -> [NSCollectionViewLayoutAttributes] {
        let allAttributes = super.layoutAttributesForElements(in: rect)
        return allAttributes.flatMap { attributes in
            switch attributes.representedElementCategory {
            case .item: return layoutAttributesForItem(at: attributes.indexPath!)
            default: return attributes
            }
        }
    }
}

但是我的 preferredLayoutAttributesFitting in Item 仍然没有调用:

override func preferredLayoutAttributesFitting(_ layoutAttributes: NSCollectionViewLayoutAttributes) -> NSCollectionViewLayoutAttributes {
        print("DSADASDADASD")
        return layoutAttributes
    }

添加测试项目:

https://github.com/Arti3DPlayer/SCollectionViewTests

As documentation write then should trigger preferredLayoutAttributesFitting method

此方法的文档还有一个 特殊注意事项 部分,即 says:

In OS X 10.11, this method is never called.

如果您想为每个项目自定义尺寸,请改用 NSCollectionViewDelegateFlowLayout 协议的 collectionView(_:layout:sizeForItemAt:) 方法:

extension ViewController : NSCollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: NSCollectionView,
                        layout collectionViewLayout: NSCollectionViewLayout,
                        sizeForItemAt indexPath: IndexPath) -> NSSize {
        return NSSize(width: self.myCollectionView.bounds.width, height: 180)
    }
}