Pull-to-Refresh →SwiftUI

Lucky Mehndiratta
1 min readJul 24, 2022

Sometimes we need to refresh the data list on the screen so that we will get the latest data from the backend. So, Pull-to-Refresh comes into the picture in this scenario. Below is the basic Pull-to-Refresh view and how you can use this to get the latest/updated data from the backend using hitting the API.

struct PullToRefresh: View {
var coordinateSpaceName: String
var onRefresh: ()->Void
@State var needRefresh: Bool = false
var
body: some View {
GeometryReader { geo in
if
(geo.frame(in: .named(coordinateSpaceName)).midY > 50) {
Spacer()
.onAppear {
needRefresh = true
}
} else if (geo.frame(in: .named(coordinateSpaceName)).maxY < 10) {
Spacer()
.onAppear {
if needRefresh {
onRefresh()
DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
needRefresh = false
}
}
}
}

HStack {
Spacer()
if needRefresh {
ProgressView()
.progressViewStyle(CircularProgressViewStyle(tint: .gray))
.opacity(needRefresh ? 1 : 0)
} else {
Text(“”)
}
Spacer()
}
}.padding(.top, -5)
}
}
How to use this

import SwiftUI
struct YourView: View {
@State var isRefreshing:Bool = false
var
body: some View {
NavigationView{
ScrollView(.vertical, showsIndicators: false){
PullToRefresh(coordinateSpaceName:”pullToRefresh”, onRefresh: {
//Call API here
}, needRefresh: isRefreshing)
Group{
//Rest UI
}
}.coordinateSpace(name: “pullToRefresh”)
}.navigationBarHidden(true)
.navigationBarTitleDisplayMode(.inline)
}
}

Happy Coding!!!

--

--