Customisable SwiftUI Refresh spinner

4.8k views Asked by At

I currently have a simple SwiftUI ScrollView that contains a single element. I have added the .refreshable(action: ) property to allow (pull down) refreshing of the view. However, this will only display the default grey spinner when pulling to refresh. Is there a way that I can change the color/style of the spinner?

2

There are 2 answers

1
Jkilaha On

Add onAppear to your List and place

  .onAppear {
                        UIRefreshControl.appearance().tintColor = .green
                        UIRefreshControl.appearance().attributedTitle = NSAttributedString("Refreshing…")
                    }
0
Wilson Muñoz On

I want to add my approach, is a very unorthodox one and I'm not saying is "the" solution, just something to discuss, hopefully it helps someone to "test" and find a better angle.

  • Also I only tested this on iOS15, not working on iOS16
  1. Make your content inside a list which will give you the .refreshable modifier and will allow pull to refresh: SWIFTUI refreshable (Pull to refresh) is not working at ScrollView

  2. Make a singleton of your UIView (this is highly unusual, but for this case may work)

     class SingletonView: UIView { 
     // Singleton instance
         static let shared : UIView = 
     SingletonView.sharedInstance(size: CGSize(width: 20, height: 20))
    
         // You can modify argument list as per your need.
         class private func sharedInstance(size : CGSize)->UIView {
             //Putting the view in the middle, but the details falls on you.
             let view = UIView(frame: CGRect(x: (UIScreen.main.bounds.width / 2) - 10, y: 0, width: size.width, height: size.height))
       //just so you can see something
         view.backgroundColor = .red
             return view
         }
    }
    
  3. Finally add this singleton view to your refresh controller and hide the original:

     .onAppear{
    //Hide the default refresh controller, attach our uiView
         //Because is a singleton it wont be added several times
         //You can always expand your singleton to be hidden, animated, removed, etc.
    UIRefreshControl.appearance().tintColor = .clear
    
    
    UIRefreshControl.appearance().addSubview(SingletonView.shared)
    
     }
    

swiftui scrollable view with custom refresh control

Gist: https://gist.github.com/Wilsonilo/309600c62c9e27385dfa5296e696b668