Better Programming

Advice for programmers.

Follow publication

Member-only story

Animations Inside a ScrollView With SwiftUI

Delay playing animations until a view is on screen

Sarah
Better Programming
Published in
3 min readJan 24, 2022
Animations Inside a ScrollView With SwiftUI

In ScrollViews and Lists, embedded views are loaded before they show up on your screen. onAppear is triggered prior to the view’s appearance on screen. We need to wait for the animated view to be on screen before playing our animation.

ViewModifier

To delay our animation, we will create a view modifier to figure out the position of the view and trigger the animation play when the view reaches the bottom of the screen.

Inside the body function, use GeometryReader to get the view’s global position. If the view is off-screen (lower on the scrollView/list), then the content will be at a position higher than the height of the screen.

What we are going to do in our code:

  • Embed our content inside GeometryReader.
  • Create a variable to get the global midY position of the view with GeometryReader.
  • Create a variable to offset the view’s midY position if needed.
  • Use an if statement to compare the screen height to the midY position and offset of the view using the variables we created. If the height of the screen is equal or higher than the midY position (+ offset), then the content will…

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Responses (1)

Write a response