您好,我已经按照raywenderlich的视频进行了自定义收藏 布局。 UICollectionViewFlowLayout的子类如下
导入UIKit
CharacterFlowLayout类:UICollectionViewFlowLayout {
让standardItemAlpha:CGFloat = 0.5
让standardItemScale:CGFloat = 0.5
var count = 0 覆盖func prepare(){
super.prepare()
}
覆盖func layoutAttributesForElements(在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)
} }
我不了解计算背后的逻辑?您能解释一下为什么我们要计算距离和比率吗?