Search code examples
swift2uicollectionviewuicollectionviewlayoutuiscrollviewdelegate

Swift 2 collection view extension for horizontal scroll to vertical


I've got this extension for my collection view that makes horizontal scroll but I want to change it on vertical scroll??

extension viewRe : UIScrollViewDelegate
{
    func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>)
    {
        let layout = self.recipesCollView?.collectionViewLayout as! UICollectionViewFlowLayout
        let cellWidthIncludingSpacing = layout.itemSize.width + layout.minimumLineSpacing

        var offset = targetContentOffset.memory
        let index = (offset.x + scrollView.contentInset.left) / cellWidthIncludingSpacing
        let roundedIndex = round(index)

        offset = CGPoint(x: roundedIndex * cellWidthIncludingSpacing - scrollView.contentInset.left, y: -scrollView.contentInset.top)
        targetContentOffset.memory = offset
    }
}

With this extension I'm trying to make the cells to stick to the TOP of the view even when he scrolls because the paging is enabled. So whenever the user scrolls i would like the cell to stick to the top and so on when the user scrolls.


Solution

  • @donnyWals is right. If you are using a UICollectionView just change its UICollectionViewFlowLayout

    let layout = UICollectionViewFlowLayout()
    layout.scrollDirection = . Horizontal
    let collectionView = UICollectionView(frame: frame, collectionViewLayout: layout)
    

    or if you have an existent UICollectionView

    if let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
        layout.scrollDirection = .Horizontal
    }
    

    Follow the official API:

    UICollectionView

    UICollectionViewFlowLayout