1. UsescrollToItem
Method scroll collection view
(deadline: .now() + 0.1) { let firstIndexPath = IndexPath(item: 0, section: 0) let lastIndexPath = IndexPath(item: - 1, section: 0) // Scroll to first item (at: firstIndexPath, at: .left, animated: false) // Delay for a short time (., 0.1 seconds) (deadline: .now() + 0.1) { // Scroll to last item (at: lastIndexPath, at: .left, animated: false) } }
In the above code, first usescrollToItem
Method scrolls the collection view to the first piece of data (aligned to the left), and then after a later delay time, use it againscrollToItem
Method scrolls it to the last piece of data (aligned to the left).
2. UsesetContentOffset
Method to scroll collection view
(deadline: .now() + 0.1) { let firstIndexPath = IndexPath(item: 0, section: 0) let lastIndexPath = IndexPath(item: - 1, section: 0) if let firstCellAttributes = (at: firstIndexPath), let lastCellAttributes = (at: lastIndexPath) { let contentOffset = CGPoint(x: - , y: 0) (contentOffset, animated: false) } }
In the above code, we usedsetContentOffset
Method to scroll the collection view. We take the layout properties of the first and last data, and then calculate the correct one based on their positioncontentOffset
value, allowing the collection view to scroll to the last piece of data.
3. UsescrollRectToVisible
Method for scrolling collection view
(deadline: .now() + 0.1) { let firstIndexPath = IndexPath(item: 0, section: 0) let lastIndexPath = IndexPath(item: - 1, section: 0) if let firstCellAttributes = (at: firstIndexPath), let lastCellAttributes = (at: lastIndexPath) { let firstRect = let lastRect = let visibleRect = CGRect(x: , y: 0, width: , height: ) (visibleRect, animated: false) } }
In the above code, we usescrollRectToVisible
Method to scroll the collection view. We take the layout properties of the first and last data, and calculate a visible rectangular area based on their position, and then scroll the rectangular area into the visible range.
This is the article about Swift ScrollView scrolling to a specific location. For more related content on Swift ScrollView setting scroll position, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!