1

Есть UICollectionView с включённым Paging и одним элементом на экран по центру. Я программно листаю ячейки по определённому событию.

Подскажите могу ли я как-то контролировать скорость движения ячейки?

Например.

Мне нужно чтобы текущая ячейка за 500мс уехала за пределы экрана. А следующая подождала 200мс и появилась в на своём месте в течении 300мс.

2 ответа 2

0

Из простого что можно придумать – Вам нужен кастомный UICollectionViewFlowLayout.

Основная идея, что на нужное событие добавлять "зазор" между элементами, сдвигая первый и затем скроллить до следующего. Грубый пример в одну сторону с результатом:

введите сюда описание изображения

// MARK: - Вызов события проскроллить до следующего элемента
#warning("только для примера, не повторять в реальной жизни")
let jellyLayout = collectionView.collectionViewLayout as! JellyFlowLayout
let indexPath = collectionView.indexPathForItem(at: view.convert(CGPoint(x: UIScreen.main.bounds.width / 2, y: 200), to: collectionView))!
// MARK: - ну как-то так.
jellyLayout.addPadding(at: indexPath)
UIView.animate(withDuration: jellyLayout.moveOutAnimationDuration) { [self] in
    // MARK: - А ещё нужно обработать если не идеально расположена ячейка или там paging сделать и т.п.
    collectionView.contentOffset = CGPoint(x: collectionView.contentOffset.x + jellyLayout.itemSize.width + jellyLayout.cellPadding, y: collectionView.contentOffset.y)
}
...
// MARK: - Набросок этого кастомного UICollectionViewFlowLayout. 
class JellyFlowLayout: UICollectionViewFlowLayout {
    private var attributesCache = [UICollectionViewLayoutAttributes]()
    private var indexPathWithPadding: IndexPath? = nil
    var cellPadding: CGFloat = 8
    var contentHeight: CGFloat = 300
    var contentWidth: CGFloat = 0
    override var collectionViewContentSize: CGSize {
        return CGSize(width: contentWidth, height: contentHeight)
    }
    // MARK: - За сколько первая ячейка "уедет"
    var moveOutAnimationDuration: TimeInterval = 0.5 * 3
    // MARK: - За сколько вторая ячейка "подтянется"
    var moveInAnimationDuration: TimeInterval = 0.3 * 3
    
    func addPadding(at indexPath: IndexPath) {
        indexPathWithPadding = indexPath
        attributesCache = []
        contentWidth = 0
        UIView.animate(withDuration: moveOutAnimationDuration) { [self] in
            collectionView?.performBatchUpdates({
                invalidateLayout()
                collectionView?.layoutIfNeeded()
            }, completion: nil)
        }
        DispatchQueue.main.asyncAfter(deadline: .now() + moveOutAnimationDuration - moveInAnimationDuration) { [self] in
            removePadding()
        }
    }

    func removePadding() {
        indexPathWithPadding = nil
        attributesCache = []
        contentWidth = 0
        UIView.animate(withDuration: moveInAnimationDuration) { [self] in
            // MARK: - Нормально двигает только с performBatchUpdates, может есть и другой вариант
            collectionView?.performBatchUpdates({
                invalidateLayout()
                collectionView?.layoutIfNeeded()
            }, completion: nil)
        }
    }
    
    override func prepare() {
        // MARK: - Здесь пересчитываем для нужных вжух. Если посчитано - игнорим.
        guard let collectionView = collectionView, attributesCache.isEmpty else {
            return
        }
        // MARK: - Тут жестко по данным для примера, одна секция с элементами
        for item in 0..<collectionView.numberOfItems(inSection: 0) {
            let indexPath = IndexPath(item: item, section: 0)
            let frame = CGRect(x: contentWidth, y: 0, width: itemSize.width, height: contentHeight)
            contentWidth += frame.width + cellPadding
            // MARK: - Вот этим добиваемся эффекта вжух за счет добавления "зазора" на ширину ячейки
            if indexPath == indexPathWithPadding {
                contentWidth += itemSize.width
            }
            let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
            attributes.frame = frame
            attributesCache.append(attributes)
        }
    }
    
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        var visibleLayoutAttributes = [UICollectionViewLayoutAttributes]()
        for attributes in attributesCache {
            if attributes.frame.intersects(rect) {
                visibleLayoutAttributes.append(attributes)
            }
        }
        return visibleLayoutAttributes
    }
    
    override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
        return attributesCache[indexPath.item]
    }
}
0

Можно так попробовать сделать:

override func viewDidLoad() {
    super.viewDidLoad()

    self.collectionView.decelerationRate = UIScrollView.DecelerationRate.fast
}

вот есть статья по данному вопросу и документация

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.