Scroll в Collection View


#1

Всем привет.
Вроде банальная задача, но что-то не могу найти ответ на неё. Есть горизонтальный collection view, у которого одна линия и в ней много элементов. Как сделать так, чтобы при скролле, если первый элемент не входит полностью, то доскролливать до следующего элемента? Пагинации при этом нет.


#2

Призываю на помощь профи форума @haymob @paketik.
Очень нужна ваша помощь!:grin:


#3

На это сообщение поступили жалобы от участников сообщества, поэтому оно временно скрыто.


#4

Реализовал через переопределение функции targetContentOffset для UICollectionViewFlowLayout следующим образом:

override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
    guard let collectionView = collectionView else { return super.targetContentOffset(forProposedContentOffset: proposedContentOffset, withScrollingVelocity: velocity) }
    
    var offsetAdjustment = CGFloat.greatestFiniteMagnitude
    let horizontalOffset = proposedContentOffset.x + collectionView.contentInset.left
    
    let targetRect = CGRect(x: proposedContentOffset.x, y: 0, width: collectionView.bounds.size.width, height: collectionView.bounds.size.height)
    
    let layoutAttributesArray = super.layoutAttributesForElements(in: targetRect)
    
    layoutAttributesArray?.forEach({ (layoutAttributes) in
        let itemOffset = layoutAttributes.frame.origin.x
        if fabsf(Float(itemOffset - horizontalOffset)) < fabsf(Float(offsetAdjustment)) {
            offsetAdjustment = itemOffset - horizontalOffset
        }
    })
    
    return CGPoint(x: proposedContentOffset.x + offsetAdjustment, y: proposedContentOffset.y)
}