'Pull down to refresh data in SwiftUI
i have used simple listing of data using List
. I would like to add pull down to refresh functionality but i am not sure which is the best possible approach.
Pull down to refresh view will only be visible when user tries to pull down from the very first index same like we did in UITableView
with UIRefreshControl
in UIKit
Here is simple code for listing data in SwiftUI
.
struct CategoryHome: View {
var categories: [String: [Landmark]] {
.init(
grouping: landmarkData,
by: { $0.category.rawValue }
)
}
var body: some View {
NavigationView {
List {
ForEach(categories.keys.sorted().identified(by: \.self)) { key in
Text(key)
}
}
.navigationBarTitle(Text("Featured"))
}
}
}
Solution 1:[1]
I needed the same thing for an app I'm playing around with, and it looks like the SwiftUI API does not include a refresh control capability for ScrollView
s at this time.
Over time, the API will develop and rectify these sorts of situations, but the general fallback for missing functionality in SwiftUI will always be implementing a struct that implements UIViewRepresentable
. Here's a quick and dirty one for UIScrollView
with a refresh control.
struct LegacyScrollView : UIViewRepresentable {
// any data state, if needed
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
func makeUIView(context: Context) -> UIScrollView {
let control = UIScrollView()
control.refreshControl = UIRefreshControl()
control.refreshControl?.addTarget(context.coordinator, action:
#selector(Coordinator.handleRefreshControl),
for: .valueChanged)
// Simply to give some content to see in the app
let label = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 30))
label.text = "Scroll View Content"
control.addSubview(label)
return control
}
func updateUIView(_ uiView: UIScrollView, context: Context) {
// code to update scroll view from view state, if needed
}
class Coordinator: NSObject {
var control: LegacyScrollView
init(_ control: LegacyScrollView) {
self.control = control
}
@objc func handleRefreshControl(sender: UIRefreshControl) {
// handle the refresh event
sender.endRefreshing()
}
}
}
But of course, you can't use any SwiftUI components in your scroll view without wrapping them in a UIHostingController
and dropping them in makeUIView
, rather than putting them in a LegacyScrollView() { // views here }
.
Solution 2:[2]
here is a simple, small and pure SwiftUI solution i made in order to add pull to refresh functionality to a ScrollView.
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 {
needRefresh = false
onRefresh()
}
}
}
HStack {
Spacer()
if needRefresh {
ProgressView()
} else {
Text("??")
}
Spacer()
}
}.padding(.top, -50)
}
}
To use it it's simple, just add it at the top of your ScrollView and give it the coordinate space of the ScrollView :
ScrollView {
PullToRefresh(coordinateSpaceName: "pullToRefresh") {
// do your stuff when pulled
}
Text("Some view...")
}.coordinateSpace(name: "pullToRefresh")
Solution 3:[3]
Here's an implementation that introspects the view hierarchy and adds a proper UIRefreshControl
to a SwiftUI List's table view: https://github.com/timbersoftware/SwiftUIRefresh
Bulk of the introspection logic can be found here: https://github.com/timbersoftware/SwiftUIRefresh/blob/15d9deed3fec66e2c0f6fd1fd4fe966142a891db/Sources/PullToRefresh.swift#L39-L73
Solution 4:[4]
from iOS 15+
NavigationView {
List(1..<100) { row in
Text("Row \(row)")
}
.refreshable {
print("write your pull to refresh logic here")
}
}
for more details: Apple Doc
Solution 5:[5]
I have tried many different solutions but nothing worked well enough for my case.
GeometryReader
based solutions had bad performance for a complex layout.
Here is a pure SwiftUI 2.0 View that seems to work well, does not decrease scrolling performance with constant state updates and does not use any UIKit hacks:
import SwiftUI
struct PullToRefreshView: View
{
private static let minRefreshTimeInterval = TimeInterval(0.2)
private static let triggerHeight = CGFloat(100)
private static let indicatorHeight = CGFloat(100)
private static let fullHeight = triggerHeight + indicatorHeight
let backgroundColor: Color
let foregroundColor: Color
let isEnabled: Bool
let onRefresh: () -> Void
@State private var isRefreshIndicatorVisible = false
@State private var refreshStartTime: Date? = nil
init(bg: Color = .white, fg: Color = .black, isEnabled: Bool = true, onRefresh: @escaping () -> Void)
{
self.backgroundColor = bg
self.foregroundColor = fg
self.isEnabled = isEnabled
self.onRefresh = onRefresh
}
var body: some View
{
VStack(spacing: 0)
{
LazyVStack(spacing: 0)
{
Color.clear
.frame(height: Self.triggerHeight)
.onAppear
{
if isEnabled
{
withAnimation
{
isRefreshIndicatorVisible = true
}
refreshStartTime = Date()
}
}
.onDisappear
{
if isEnabled, isRefreshIndicatorVisible, let diff = refreshStartTime?.distance(to: Date()), diff > Self.minRefreshTimeInterval
{
onRefresh()
}
withAnimation
{
isRefreshIndicatorVisible = false
}
refreshStartTime = nil
}
}
.frame(height: Self.triggerHeight)
indicator
.frame(height: Self.indicatorHeight)
}
.background(backgroundColor)
.ignoresSafeArea(edges: .all)
.frame(height: Self.fullHeight)
.padding(.top, -Self.fullHeight)
}
private var indicator: some View
{
ProgressView()
.progressViewStyle(CircularProgressViewStyle(tint: foregroundColor))
.opacity(isRefreshIndicatorVisible ? 1 : 0)
}
}
It uses a LazyVStack
with negative padding to call onAppear
and onDisappear
on a trigger view Color.clear
when it enters or leaves the screen bounds.
Refresh is triggered if the time between the trigger view appearing and disappearing is greater than minRefreshTimeInterval
to allow the ScrollView
to bounce without triggering a refresh.
To use it add PullToRefreshView
to the top of the ScrollView
:
import SwiftUI
struct RefreshableScrollableContent: View
{
var body: some View
{
ScrollView
{
VStack(spacing: 0)
{
PullToRefreshView { print("refreshing") }
// ScrollView content
}
}
}
}
Gist: https://gist.github.com/tkashkin/e5f6b65b255b25269d718350c024f550
Solution 6:[6]
Hi check out this library I made: https://github.com/AppPear/SwiftUI-PullToRefresh
You can implement it by one line of code:
struct CategoryHome: View {
var categories: [String: [Landmark]] {
.init(
grouping: landmarkData,
by: { $0.category.rawValue }
)
}
var body: some View {
RefreshableNavigationView(title: "Featured", action:{
// your refresh action
}){
ForEach(categories.keys.sorted().identified(by: \.self)) { key in
Text(key)
Divider() // !!! this is important to add cell separation
}
}
}
}
}
Solution 7:[7]
To be honest none of the top-rated answers really worked well for my scenario. The scenario had switching between the ScrollView
and a custom LoadingView
. And every time I switched from the LoadingView
to the ScrollView
which is created using the legacy UIScrollView
using UIViewRepresentable
the contentSize
gets messed up.
So as a solution, I have created a library so that this might be useful for all the devs out there who are trying to find a solution for such a simple problem. I've taken good bits from around the internet went through many sites and finally tweaked the solution which ended up giving me the best solution.
Steps
- Add
SPM
https://github.com/bibinjacobpulickal/BBRefreshableScrollView to your project. import BBRefreshableScrollView
to the required file.- Update the
View
'sbody
.
struct CategoryHome: View {
...
var body: some View {
NavigationView {
BBRefreshableScrollView { completion in
// do refreshing stuff here
} content: {
ForEach(categories.keys.sorted().identified(by: \.self)) { key in
Text(key)
}
}
.navigationBarTitle(Text("Featured"))
}
}
}
For more details, you can follow the Readme.
Solution 8:[8]
This is a pure SwiftUI approach using a ScrollView, GeometryReader and PreferenceKey I'm able to read the scroll offset in the ScrollView and once it gets higher than a threshold I can perform an action
import SwiftUI
struct RefreshableView<Content:View>: View {
init(action: @escaping () -> Void, @ViewBuilder content: @escaping () -> Content) {
self.content = content
self.refreshAction = action
}
var body: some View {
GeometryReader { geometry in
ScrollView {
content()
.anchorPreference(key: OffsetPreferenceKey.self, value: .top) {
geometry[$0].y
}
}
.onPreferenceChange(OffsetPreferenceKey.self) { offset in
if offset > threshold {
refreshAction()
}
}
}
}
private var content: () -> Content
private var refreshAction: () -> Void
private let threshold:CGFloat = 50.0
}
fileprivate struct OffsetPreferenceKey: PreferenceKey {
static var defaultValue: CGFloat = 0
static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {
value = nextValue()
}
}
This is an example of usage of RefreshableView. The progress indicator is not included in RefreshableView, that only provides a GeometryReader and a ScrollView including the content you want to refresh. You need to provide a ProgressView or another view to show loading is in progress. It doesn't work with List, but you can use ForEach instead and the content will scroll thanks to the ScrollView
RefreshableView(action: {
viewModel.refreshFeed(forceReload: true)
}) {
if viewModel.showProgressView {
VStack {
ProgressView()
Text("reloading feed...")
.font(Font.caption2)
}
}
ForEach(viewModel.feed.entries) { entry in
viewForEntry(entry)
}
}
Full example can be found on GitHub
Solution 9:[9]
The swiftui-introspects has not supported on masOS yet, so if you are going to build a UI that works for both iOS and macOS, consider the Samu Andras library.
I forked his code, added a few enhancements, and added the ability to use without the NavigationView
Here is the sample code.
RefreshableList(showRefreshView: $showRefreshView, action:{
// Your refresh action
// Remember to set the showRefreshView to false
self.showRefreshView = false
}){
ForEach(self.numbers, id: \.self){ number in
VStack(alignment: .leading){
Text("\(number)")
Divider()
}
}
}
For more details, you can visit the link below. https://github.com/phuhuynh2411/SwiftUI-PullToRefresh
Solution 10:[10]
what about this
import SwiftUI
public struct FreshScrollView<Content>: View where Content : View{
private let content: () -> Content
private let action: () -> Void
init(@ViewBuilder content: @escaping () -> Content, action: @escaping ()-> Void){
self.content = content
self.action = action
}
@State var startY: Double = 10000
public var body: some View{
ScrollView{
GeometryReader{ geometry in
HStack {
Spacer()
if geometry.frame(in: .global) .minY - startY > 30{
ProgressView()
.padding(.top, -30)
.animation(.easeInOut)
.transition(.opacity)
.onAppear{
let noti = UIImpactFeedbackGenerator(style: .light)
noti.prepare()
noti.impactOccurred()
action()
}
}
Spacer()
}
.onAppear {
startY = geometry.frame(in:.global).minY
}
}
content()
}
}
}
#if DEBUG
struct FreshScrollView_Previews: PreviewProvider {
static var previews: some View {
FreshScrollView {
Text("A")
Text("B")
Text("C")
Text("D")
} action: {
print("text")
}
}
}
#endif
Solution 11:[11]
I was pretty dissatisfied with the options for pull to refresh in SwiftUI. Even when using the introspect UIKit based solutions, there were strange behaviors and some view jumping when using navigation views. I also needed something a bit more customizable so I wrote a library. It's a (nearly) pure SwiftUI implementation of a pull to refresh control and it works on both iOS 14 and 15.
https://github.com/gh123man/SwiftUI-Refresher
It's highly customizable and supports some extra features like being able to overlay the view contents (in cases where you have a static header).
Solution 12:[12]
I know original question was for the List, but here is the code for the ScrollView
and LazyVStack
, since sometimes list is not appropriate.
import SwiftUI
struct PullToRefreshSwiftUI: View {
@Binding private var needRefresh: Bool
private let coordinateSpaceName: String
private let onRefresh: () -> Void
init(needRefresh: Binding<Bool>, coordinateSpaceName: String, onRefresh: @escaping () -> Void) {
self._needRefresh = needRefresh
self.coordinateSpaceName = coordinateSpaceName
self.onRefresh = onRefresh
}
var body: some View {
HStack(alignment: .center) {
if needRefresh {
VStack {
Spacer()
ProgressView()
Spacer()
}
.frame(height: 100)
}
}
.background(GeometryReader {
Color.clear.preference(key: ScrollViewOffsetPreferenceKey.self,
value: $0.frame(in: .named(coordinateSpaceName)).origin.y)
})
.onPreferenceChange(ScrollViewOffsetPreferenceKey.self) { offset in
guard !needRefresh else { return }
if abs(offset) > 50 {
needRefresh = true
onRefresh()
}
}
}
}
struct ScrollViewOffsetPreferenceKey: PreferenceKey {
typealias Value = CGFloat
static var defaultValue = CGFloat.zero
static func reduce(value: inout Value, nextValue: () -> Value) {
value += nextValue()
}
}
And here is typical usage:
struct ContentView: View {
@State private var refresh: Bool = false
@State private var itemList: [Int] = {
var array = [Int]()
(0..<40).forEach { value in
array.append(value)
}
return array
}()
var body: some View {
ScrollView {
PullToRefreshSwiftUI(needRefresh: $refresh,
coordinateSpaceName: "pullToRefresh") {
DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
withAnimation { refresh = false }
}
}
LazyVStack {
ForEach(itemList, id: \.self) { item in
HStack {
Spacer()
Text("\(item)")
Spacer()
}
}
}
}
.coordinateSpace(name: "pullToRefresh")
}
}
Solution 13:[13]
Since it is for swiftUi its better to use pure swiftUi as @Anatoliy Kashkin mentioned in his answer , So i've updated his answer to support enable/disable refreshing from outside and inside the view .
Create PullToRefresh
struct View :
import Foundation
import SwiftUI
struct PullToRefresh: View {
@Binding var isRefreshing:Bool
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 {
needRefresh = false
onRefresh()
}
}
}
HStack {
Spacer()
if needRefresh || isRefreshing {
ProgressView()
} else {
Image(systemName: "arrow.clockwise")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 20, height: 20)
.foregroundColor(.gray)
Text("Refresh")
.foregroundColor(.gray)
}
Spacer()
}
}.padding(.top, isRefreshing ? 0 : -50)
}
}
Now u can use it like this :
@State var isRefreshing:Bool = true
var body: some View {
ScrollView(){
PullToRefresh(isRefreshing: $isRefreshing, coordinateSpaceName: "pullToRefresh") {
fetchOrders()
}
VStack(alignment : .leading){
Text("Some view...")
}
}.coordinateSpace(name: "pullToRefresh")
By setting isRefreshing
true , its will show the progress and set it to false when you finish ur http request or updating data etc
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow