Member-only story

How to make Pure SwiftUI pull to refresh?

Pull down to refresh data in SwiftUI — Xcode 12-iOS 14

--

In this tutorial, We are going to implement Pull to refresh using only SwiftUI components.

We are going to divide this problem in two parts:

  1. Logic to detect if user pull down the scroll view
  2. Add Progress view and pull down loader animations

Logic to detect if user pull down the scroll view, We are going to use coordinator space of ScrollView with Child GeometryReader view. This will help us evaluate if user have pulled the view and How much user have pulled the view. If user have pulled the scroll view significantly (50 px in our case). We will consider user want to force reload view.

Add Progress view and pull down loader animations, If refresh is called we only want to show ProgressView(). But if user pull down we need to show a static progress bar, who’s bar becomes visible on scroll down. to achieve this we need to mimic a progress bar using VStack and rotationEffect.

ForEach(0..<8) { tick in
VStack {
Rectangle()
.fill(Color(UIColor.tertiaryLabel))
.opacity(
(Int((geo.frame(in: coordinateSpace).midY)/7) < tick)
? 0 : 1) //show bar based on how much view been pulled down
.frame(width: 3, height: 7)
.cornerRadius(3)
Spacer()
}.rotationEffect(Angle.degrees(Double(tick)/(8) * 360))
}.frame(width: 20, height: 20, alignment: .center)

Also, We need to move our RefreshControl view under Navigation so add an offset. So the final code look like following:

--

--

Prafulla Singh
Prafulla Singh

Responses (3)