Skip to main content

How to detect whether a scrollview is currently moving or is idle

About 2 minSwiftSwiftUIArticle(s)bloghackingwithswift.comcrashcourseswiftswiftuixcodeappstore

How to detect whether a scrollview is currently moving or is idle 관련

SwiftUI by Example

Back to Home

How to detect whether a scrollview is currently moving or is idle | SwiftUI by Example

How to detect whether a scrollview is currently moving or is idle

Updated for Xcode 16

Improved in iOS 18

SwiftUI’s onScrollPhaseChange() modifier lets us detect when the movement of a scrollview changes somehow.

For example, this changes a color from red to green whenever the user is actively interacting with it:

struct ContentView: View {
    @State private var backgroundColor = Color.red

    var body: some View {
        ScrollView {
            backgroundColor
                .frame(height: 2000)
        }
        .onScrollPhaseChange { oldPhase, newPhase in
            if newPhase == .interacting {
                backgroundColor = .green
            } else {
                backgroundColor = .red
            }
        }
    }
}

Download this as an Xcode projectopen in new window

The oldPhase and newPhase values can have one of five different values:

  • .animating: When the scrollview is moving towards one particular view.
  • .decelerating: When the user has released their finger and the scrollview is slowing down naturally.
  • .idle: The scrollview is not moving or being interacted with.
  • .interacting: The user has their finger down right now, either stationary or moving.
  • .tracking: Used when the system thinks a user scroll event might be coming soon; I suspect this one isn't so helpful.

Having access to both the old and new values allows you to add subtle interactions – perhaps moving to idle after a drag triggers one result, whereas doing so after an animation triggers a different result.

Similar solutions…
How to flash the scroll bar indicators of a ScrollView or List | SwiftUI by Example

How to flash the scroll bar indicators of a ScrollView or List
How to add horizontal and vertical scrolling using ScrollView | SwiftUI by Example

How to add horizontal and vertical scrolling using ScrollView
How to scroll to exact locations inside a scrollview | SwiftUI by Example

How to scroll to exact locations inside a scrollview
How to indent the content or scroll indicators in a ScrollView | SwiftUI by Example

How to indent the content or scroll indicators in a ScrollView
How to disable ScrollView clipping so contents overflow | SwiftUI by Example

How to disable ScrollView clipping so contents overflow

이찬희 (MarkiiimarK)
Never Stop Learning.