UICollectionView基础进阶(二)——— UICollectionViewLayout自定义

前言

这篇文章主要介绍了UICollectionViewLayout的自定义的实现,只要学会基本的定义,更复杂的也不会太难,文末介绍了UICollectionView使用自定义Layout实现的动画,我会用简单的实例来解释,文章中还有在实战中遇到的问题也写出来以供参考,这篇文章是我的总结与实战,原创文章,转载请注明出处。


UICollectionView强大的原因UICollectionViewLayout

  • UICollectionViewLayout可以定制你想要的几乎所有布局,每一个Cell不同的大小,Cell的间距,Supplementary Views的样式不一定是作为Header View而是随着布局在任何地方,但是要记住,Supplementary Views一定要继承自UICollectionReusableView,视图也要在CollectionView中注册。
  • UICollectionViewLayout可以根据内容来计算各视图的大小和位置

回归题目

CollectionViewContentSize

  • CollectionView不知道自己的ContentSize的大小,UICollectionView继承自UIScrollView,所以这里CollectionViewContentSize是完整的UICollectionView的大小,而不是可视Bounds的大小。ContentSize的大小可以完全根据内容定制,甚至可以随着内容的变化动态改变,就像UITableView自动实现的那样。

  • 在Demo里我使用Cell的大小和Supplementary Views的大小动态返回ContentSize的大小

    override var collectionViewContentSize: CGSize {
        if let collectionView = self.collectionView {
            let width = collectionView.frame.width
            var height = collectionView.frame.height
            
            if let count = cellCount {
                height = reusableViewSize.height
                height += CGFloat(count) * (itemSize.height + distance)
            }
            
            return CGSize(width: width, height: height)
        }
        return CGSize()
    }

prepare方法的调用

  • 在prepare方法里,可以用来为一些变量初始化,但在Swift里,可以使用Getter属性来返回值,一些Size的初始化也可以写在这里,或Objective-C可以将一些初始化逻辑写在这里
  • 但要记得调用supre.prepare(),除非你想自己实现系统为你实现的内容

LayoutAttributesForElements

这是很重要的方法

  • layoutAttributesForElements 为rect中的可见的视图提供Attributes,并使用LayoutAttributesForItem和LayoutAttributesSupplementaryView为对应的视图赋值。
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        var attributes = [UICollectionViewLayoutAttributes]()
        
        if let count = cellCount {
            for index in 0..<count {
                let indexPath = IndexPath(item: index, section: 0)
                if let attribute = layoutAttributesForItem(at: indexPath) {
                    attributes.append(attribute)
                }
            }
        }
        
        let headerIndexPath = IndexPath(item: 0, section: 0)
        if let attribute = layoutAttributesForSupplementaryView(ofKind: "HeaderView", at: headerIndexPath) {
            attributes.append(attribute)
        }
        
        return attributes
    }

LayoutAttributesForItem 和 LayoutAttributesForSupplementaryView

attributes可以设置以下属性

  • frame
  • size
  • center
  • transform3D
  • alpha
  • zIndex
  • isHidden

这两个属性是用来设置Cell和对应的Supplementart View的attributes并返回该attributes,设置的属性情况可以在layoutAttributesForElements(in rect:)中被调用,并被用于相应的Cell和View

    override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
        let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
        attributes.size = itemSize
        attributes.center = configureCellCenter(from: indexPath)
        
        return attributes
    }
    
    override func layoutAttributesForSupplementaryView(ofKind elementKind: String, at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
        let attributes = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: elementKind, with: indexPath)
        attributes.size = reusableViewSize
        attributes.center = reusableViewCenter
        
        return attributes
    }

动画

perpare(forCollectionViewUpdates:)

这个方法包含一个参数,使用这个参数可以获得当前更新的状况,.delete,.insert,使用该方法可以将即将变化的Cell的indexPath使用数组存储下来,并在使用时返回,可以看作为更新状态做初始化。

    override func prepare(forCollectionViewUpdates updateItems: [UICollectionViewUpdateItem]) {
        super.prepare(forCollectionViewUpdates: updateItems)
        
        if self.deleteIndexPath.count != 0 || self.insertIndexPath.count != 0 {
            self.deleteIndexPath.removeAll()
            self.insertIndexPath.removeAll()
        }
        for update in updateItems {
            if update.updateAction == .delete,
                let indexPath = update.indexPathBeforeUpdate {
                self.deleteIndexPath.append(indexPath)
            } else if update.updateAction == .insert,
                let indexPath = update.indexPathAfterUpdate {
                self.insertIndexPath.append(indexPath)
            }
        }
    }

initialLayoutAttributesForAppearingItem

这个方法为即将出现的Item出现在屏幕上的Item做初始化,我在这个方法里将Item的初始Center设置在Supplementary View的中点,并将Aplha初始化为0,这样看起来就像Item是飞到自己的位置上去的

    override func initialLayoutAttributesForAppearingItem(at itemIndexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
        var attributes = super.initialLayoutAttributesForAppearingItem(at: itemIndexPath)
        
        if self.insertIndexPath.contains(itemIndexPath) {
            if attributes != nil {
                attributes = layoutAttributesForItem(at: itemIndexPath)
                attributes?.alpha = 0.0
                attributes?.center = reusableViewCenter
            }
        }
        return attributes
    }

finalLayoutAttributesForDisappearingItem

这个方法用来给即将消失的Item做准备,我在这个方法里,让Item翻转缩小并移动到Supplementary View的Center最终消失

    override func finalLayoutAttributesForDisappearingItem(at itemIndexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
        var attributes = super.finalLayoutAttributesForDisappearingItem(at: itemIndexPath)
        
        if self.deleteIndexPath.contains(itemIndexPath) {
            if attributes != nil {
                attributes = layoutAttributesForItem(at: itemIndexPath)
                
                attributes?.alpha = 0.0
                attributes?.center = reusableViewCenter
                attributes?.transform3D = CATransform3DMakeScale(0.1, 0.1, 0.1)
                attributes?.transform3D = CATransform3DMakeRotation(2.0, 2.0, 2.0, 2.0)
            }
        }
        
        return attributes
    }

finalizeCollectionViewUpdates

这个方法在整个更新结束后,做一些状态上的更新

    override func finalizeCollectionViewUpdates() {
        super.finalizeCollectionViewUpdates()
        
        self.insertIndexPath.removeAll()
        self.deleteIndexPath.removeAll()
    }

总结:UICollectionViewLayout的自定义介绍就这么多,更加酷炫的效果往往建立在基础上,当你学会一些基础更加好的动画就不在话下了。

发布了4 篇原创文章 · 获赞 1 · 访问量 123

猜你喜欢

转载自blog.csdn.net/weixin_41473928/article/details/104210369