Search code examples
iosswiftuitableviewscrollposition

How can I reset UICollectionView scroll position using swift?


I'm using a UITableView with UITableViewCells inside which within it has a UICollectionView. The first item in each UICollectionView is a header cell which I don't want to focus on.

func collectionView(collectionView: UICollectionView, canFocusItemAtIndexPath indexPath: NSIndexPath) -> Bool {
        if indexPath.row == 0 {
            // TODO: scroll to correct position here
            return false
        }
        return true
    }

So the furthest left I will focus on, is the first cell to the right of the header cell (at index 1). Issue that comes up is -- when scrolling right, and the cells scroll offscreen and I scroll back to the left, since I can't focus on the first item, the header cell is forever offscreen since the scroll position doesn't update. How can I update the scroll position programmatically?


Solution

  • Adding this line is what worked. indexPath in this case is equal to the NSIndexPath of the first cell.

    collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: true)