Hi Brian, I have a uicollectionview where i fetch new data from API, and then insert in collectioview, after inserting its scroll position changes and it scrolls up, how to maintain the scroll position after inserting cell? please help. Below is the code for reference
APIRequest.shared().fetchAgewiseSearch(params: params) { [unowned self] (urlResponse, data, error) in
if let error = error {
print("error fetching candidates", error)
}
if let data = data {
do {
let response = try jsonDecoder.decode(AgewiseSearchResponse.self, from: data)
if response.candidates.count == 0 {
self.isDonePaginating = true
}
//self.items += response.candidates
self.bottomOffset += self.collectionView.contentSize.height - self.collectionView.contentOffset.y
CATransaction.begin()
CATransaction.setDisableActions(true)
self.collectionView.performBatchUpdates({
for i in 0..<response.candidates.count {
self.items.append(response.candidates[i])
let indexPath = IndexPath(item: self.items.count - 1, section: 0)
self.collectionView.insertItems(at: [indexPath])
}
}, completion: { (success) in
//self.collectionView.contentSize.height - bottomOffset
let offset = CGPoint(x: 0, y: self.bottomOffset)
self.collectionView.setContentOffset(offset, animated: false)
//self.bottomOffset += self.collectionView.contentSize.height
//self.collectionView.contentOffset = CGPoint(x: 0, y: self.collectionView.contentSize.height - self.bottomOffset)
self.stopIndex = response.stopIndex
self.lastIndex = response.lastIndex
self.isPaginating = false
self.collectionView.collectionViewLayout.invalidateLayout()
self.collectionView.layoutSubviews()
CATransaction.commit()
})
} catch {
print("error parsing candidats", error)
}
}
}