UICollectionView 奇怪记录

Posted by Yxi on March 6, 2021

“Yeah It’s on. ”

前言

记录UICollectionView踩坑记录

UICollectionView

layoutAttributes

问题:collectionView 的 layoutAttributes 相关属性和方法在小于iOS12系统上会出现奇奇怪怪的输出。

if #available(iOS 12.0, *) { // iOS System Version >= 12, po 打印如下,均正常。

1
2
3
4
    po collectionView.layoutAttributesForItem(at: IndexPath(item: 0, section: 0))
    
    Optional<UICollectionViewLayoutAttributes>
        - some: <UICollectionViewLayoutAttributes: 0x7ff4cbf0dc40> index Path: (<NSIndexPath: 0x9040f1852eb7911b>) {length = 2, path = 0 - 0}; frame = (0 0; 50 50);

1
2
    po collectionView.layoutAttributesForItem(at: IndexPath(item: 0, section: 1))
    nil

} else { // iOS System Version < 12, po 打印如下,异常

1
2
3
4
5
    po collectionView.layoutAttributesForItem(at: IndexPath(item: lastItem, section: lastSection))
    
    Optional<UICollectionViewLayoutAttributes>
        - some: NSColor

1
2
    po collectionView.layoutAttributesForItem(at: IndexPath(item: 0, section: 1))
    0

}

解决方案: 单独判断类型,如下

if let attributes = collectionView.layoutAttributesForItem(at: IndexPath(item: 0, section: 1)) {
    attributes.isMember(of: UICollectionViewLayoutAttributes.self) {
    
    } else {
        // do somethind
    }

}