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的自定义介绍就这么多,更加酷炫的效果往往建立在基础上,当你学会一些基础更加好的动画就不在话下了。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
如果你想在一个 UICollectionView实现两个小的 item 和一个大的 item 的布局,可以利用 UICollectionViewDelegateFlowLayout 协议的方法进行实现。 具体思路如下: 1. 首先确定一个大的 item 和两个小的 item 的大小,可以使用两个 CGFloat 类型的常量来表示。 2. 然后,在 collectionView(_:layout:sizeForItemAt:) 方法中,根据每个 item 所在的 indexPath,判断当前的 item 是大的 item 还是小的 item,并返回对应的大小。可以使用三目运算符或者 switch 语句来实现。 3. 最后,在 collectionView(_:layout:insetForSectionAt:) 方法中,设置 section 的内边距,使得大的 item 和小的 item 的排列能够正确地对齐。 下面是一个示例代码: ```swift class MyViewController: UIViewController { let bigItemSize: CGFloat = 200 let smallItemSize: CGFloat = 100 let itemSpacing: CGFloat = 10 let sectionInset: UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) // ... 其他代码 ... } extension MyViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { if indexPath.item % 3 == 0 { // 大的 item return CGSize(width: bigItemSize, height: bigItemSize) } else { // 小的 item return CGSize(width: smallItemSize, height: smallItemSize) } } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return sectionInset } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return itemSpacing } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return itemSpacing } } ``` 在上面的例子中,我们假设每行有三个 item,其中每个大的 item 占据一行,每个小的 item 占据一列。因此,在 minimumLineSpacingForSectionAt 和 minimumInteritemSpacingForSectionAt 方法中,我们都返回了 itemSpacing,即 item 之间的间距。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值