zepojo/UPCarouselFlowLayout

Is there a way to know if the item is in the center?

Closed this issue · 3 comments

Hello guys,

I'm searching a way to make appear some information when the item is in the center, and make it's disappear when it's not.

Is it possible with UPCarouselFlowLayout?
Or Do you have any idea where I can make a callback to get the state of an item?

regards,

@Phenek ,

var indexNumber:Int = 0

func scrollViewDidScroll(_ scrollView: UIScrollView) {

    let center = CGPoint(x: scrollView.contentOffset.x + (scrollView.frame.width / 2), y: (scrollView.frame.height / 2))

    if let indexNumbers = collectionView.indexPathForItem(at: center) {

        indexNumber = indexNumbers.row

    }

    

}

@Phenek
you can create delegate

protocol UPCarouselFlowLayoutDelegate: class {
func carouselFlowLayout(_ flowLayout: UPCarouselFlowLayout, didCenter index: Int)
}

here you can add delegate methods

if isHorizontal {
let closest = layoutAttributes.sorted { abs($0.center.x - proposedContentOffsetCenterOrigin) < abs($1.center.x - proposedContentOffsetCenterOrigin) }.first ?? UICollectionViewLayoutAttributes()
targetContentOffset = CGPoint(x: floor(closest.center.x - midSide), y: proposedContentOffset.y)
here you have
delegate?.carouselFlowLayout(self, didCenter: closest.indexPath.row)
}
else {
let closest = layoutAttributes.sorted { abs($0.center.y - proposedContentOffsetCenterOrigin) < abs($1.center.y - proposedContentOffsetCenterOrigin) }.first ?? UICollectionViewLayoutAttributes()
targetContentOffset = CGPoint(x: proposedContentOffset.x, y: floor(closest.center.y - midSide))
here you have
delegate?.carouselFlowLayout(self, didCenter: closest.indexPath.row)
}

dx777 commented

@yuratrotskyi
Thank you so much, works like a charm!