0
  • 你好,我已经关注了 raywenderlich 的视频来进行集合视图自定义布局。UICollectionViewFlowLayout 的子类如下

    导入 UIKit

    类 CharacterFlowLayout: UICollectionViewFlowLayout {

    让standardItemAlpha: CGFloat = 0.5
    让standardItemScale: CGFloat = 0.5

    var count = 0 覆盖 func prepare() {

    超级准备()

    }

覆盖 func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]?{

   let attributes = super.layoutAttributesForElements(in: rect)

   var attributesCopy = [UICollectionViewLayoutAttributes]()

   for itemAttributes in attributes! {
     let itemAttributesCopy = itemAttributes.copy() as! UICollectionViewLayoutAttributes

     changeLayoutAttributes(itemAttributesCopy)

     attributesCopy.append(itemAttributesCopy)

   }

   return attributesCopy  

}

    **override open func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool** {

   return true

   }

    **func changeLayoutAttributes(_ attributes: UICollectionViewLayoutAttributes)** {


   let collectionCenter = collectionView!.frame.size.height/2

   let offset = collectionView!.contentOffset.y // bounds

   let normalizedCenter = attributes.center.y - offset

   let maxDistance = self.itemSize.height + self.minimumLineSpacing

   let distance = min(abs(collectionCenter - normalizedCenter), maxDistance)

   let ratio = (maxDistance - distance)/maxDistance

   let alpha = ratio * (1 - self.standardItemAlpha) + self.standardItemAlpha

   let scale = ratio * (1 - self.standardItemScale) + self.standardItemScale

   attributes.alpha = alpha

   attributes.transform3D =  CATransform3DScale(CATransform3DIdentity, scale, scale, 1)
      }    }

我不明白计算背后的逻辑?你能解释一下为什么我们要计算距离和比率吗?

4

0 回答 0