SoFunction
Updated on 2025-04-11

Swift How to make ScrollView scroll to a specific location

1. UsescrollToItemMethod 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 usescrollToItemMethod scrolls the collection view to the first piece of data (aligned to the left), and then after a later delay time, use it againscrollToItemMethod scrolls it to the last piece of data (aligned to the left).

2. UsesetContentOffsetMethod 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 usedsetContentOffsetMethod 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 positioncontentOffsetvalue, allowing the collection view to scroll to the last piece of data.

3. UsescrollRectToVisibleMethod 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 usescrollRectToVisibleMethod 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!