swift的一个横向滚动居中变大的layout
class CenterLayout: UICollectionViewFlowLayout {
// let kZoomFactor = 0.1
// let kActiveDistanse = 200.0
let kMaxCellWidth:CGFloat = 168
let kMinCellWidth:CGFloat = 152
let kMaxCellHeight:CGFloat = 504
let kMinCellHeight:CGFloat = 456
override init() {
super.init()
self.initParams()
}
requiredinit?(coder aDecoder:NSCoder) {
super.init(coder: aDecoder)
self.initParams()
}
func initParams() {
self.itemSize = CGSize.init(width: kMaxCellWidth, height: kMaxCellHeight)
self.scrollDirection = .horizontal
self.minimumLineSpacing = 7.5
self.minimumInteritemSpacing = KScreenHeight
let insert = (KScreenWidth-kMaxCellWidth)/2
self.sectionInset=UIEdgeInsetsMake(0,insert, 0,insert)
}
overridefuncshouldInvalidateLayout(forBoundsChange newBounds:CGRect) ->Bool{
return true
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
letarray =super.layoutAttributesForElements(in: rect)
let pPoint = self.collectionView?.contentOffset ?? CGPoint.zero
let pSize = self.collectionView?.bounds.size ?? CGSize.init(width: kMinCellWidth, height: kMinCellHeight)
letvisibleRect =CGRect.init(origin: pPoint, size: pSize)
array?.forEach({ (attributes)in
ifrect.intersects(attributes.frame){
vardistance =Double(visibleRect.midX-attributes.center.x)
distance =abs(distance)
letmaxDistance =KScreenWidth/2
letmaxZoom =max((maxDistance-CGFloat(distance))/maxDistance,0)
let fWidth = kMinCellWidth + (kMaxCellWidth - kMinCellWidth) * maxZoom
let fHeight = kMinCellHeight + (kMaxCellHeight - kMinCellHeight) * maxZoom
attributes.size=CGSize.init(width: fWidth, height: fHeight)
}
})
returnarray;
}
overridefunctargetContentOffset(forProposedContentOffset proposedContentOffset:CGPoint, withScrollingVelocity velocity:CGPoint) ->CGPoint{
var offsetAdjustment = CGFloat.greatestFiniteMagnitude
lethorizontalCenter = proposedContentOffset.x+(self.collectionView!.bounds.size.width/2.0)
lettargetRect =CGRect.init(x: proposedContentOffset.x, y: 0.0, width:self.collectionView!.bounds.size.width, height:self.collectionView!.bounds.size.height)
letarray =super.layoutAttributesForElements(in: targetRect)
array?.forEach({ (layoutAttributes)in
letitemHorizontalCenter = layoutAttributes.center.x
if(abs(itemHorizontalCenter-horizontalCenter)
offsetAdjustment = itemHorizontalCenter-horizontalCenter;
}
})
letptTarget =CGPoint.init(x: proposedContentOffset.x+offsetAdjustment, y: proposedContentOffset.y)
return ptTarget
}
}