//
//  PDFRollViewFlowLayout.swift
//  PrinterDemo
//
//  Created by ios on 2021/12/18.
//  Copyright © 2021 Printer. All rights reserved.
//

import UIKit

class PDFRollViewFlowLayout: UICollectionViewFlowLayout {

    override func prepare() {
        super.prepare()
        
        let inset = (self.collectionView!.frame.size.width - self.itemSize.width) / 2
        self.sectionInset = UIEdgeInsets.init(top: 0, left: inset, bottom: 0, right: inset)
    }
    
    override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
        return true
    }
    
    //返回所有cell的布局属性以及整体排布
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        
        return super.layoutAttributesForElements(in: rect)
    }
    
    override open func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
        guard let collectionView = collectionView else { return proposedContentOffset }
        let size = collectionView.frame.size
        let rect = CGRect(x: proposedContentOffset.x, y: proposedContentOffset.y, width: size.width, height: size.height)
        
        guard let elementArray = super.layoutAttributesForElements(in: rect) else { return proposedContentOffset }
        
        var minDetal = MAXFLOAT
        let centerX = proposedContentOffset.x + size.width * 0.5;
        for attrs in elementArray {
            
            if abs(minDetal) > Float(abs(centerX - attrs.center.x)) {
                minDetal = Float(attrs.center.x - centerX)
            }
        }
        return CGPoint(x: proposedContentOffset.x + CGFloat(minDetal), y: proposedContentOffset.y)
    }
}
