Syed Tariq
Syed Tariq

Reputation: 2918

How can I scroll a collection view cell to the middle of the visible area

I am using UICollectionView to create a single row of cells which serve as an index to display a table view section with more details. The user can scroll the cells and select a particular cell which brings up the corresponding detail by scrolling a UITableview section below. This works fine. I would like a specific cell to be roughly in the middle of the row of visible cells when the view is first shown after being segued from a previous screen. Is there something comparable to scrollTableTo in collection view? In How to scroll to a particular index in collection view in swift there is a reference to scrollToItem but I need help understanding how to use it. It compiles and executes in viewDidAppear. The UITableview is scrolled as expected. The item i in the code segment cell is the item I want displayed. However, the cells are not changed (The first item on the list is displayed on the left). What works is the same statement in the shouldSelectAt. The cell that was selected is centered in the visible set.

   override func viewDidAppear(_ animated: Bool) {
    // DOES NOT WORK
    var i = 0
    for workorder in dm.workOrderNames {
        if (workOrderToBeDisplayed == workorder) {
            scrollTableTo(section: i, row: 0)
            print("workorder = \(workorder) i = \(i)")
            return
        }
        i = i + 1
    }

    workOrderView.scrollToItem(at:IndexPath(item: i, section: 0), at: .centeredHorizontally, animated: false)
}

func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
 // WORKS 
 workOrderView.scrollToItem(at:IndexPath(item: indexPath.item, section: 0), at: .centeredHorizontally, animated: false)
    return true
}

Upvotes: 1

Views: 2461

Answers (1)

Fetrindade
Fetrindade

Reputation: 31

You can try this

override func viewWillAppear(_ animated: Bool) {
        self.yourCollection.scrollToItem(at: IndexPath(item: collectionSize/2, section: 0), at: .centeredHorizontally, animated: false)
    }
}

Upvotes: 1

Related Questions