UIRefreshControl spins too fast - ios

I want to trigger refreshControl to show automatically when a tableView is initializing its data from server, and I have tried several ways in this question
UIRefreshControl - beginRefreshing not working when UITableViewController is inside UINavigationController
The refreshControl did show when the data is being initialized at the begining, but it spins too fast(maybe 2x the normal speed).
Does anyone know the reason and how to solve this problem?

Here is the code
override func viewDidLoad() {
super.viewDidLoad()
networkManager = BookNetworkManager(userAccount: userAccount)
HUD = JGProgressHUD.standard
refreshControl!.addTarget(self, action: #selector(refreshData), for: .valueChanged)
tableView.tableFooterView = UIView()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
delegate?.setNavgationItem(status: .none)
if !loaded {
tableView.setContentOffset(CGPoint(x: 0, y: -self.refreshControl!.height - self.topLayoutGuide.length), animated: true)
refreshControl!.beginRefreshing()
refreshData()
loaded = true
}
}
func refreshData() {
delegate?.hidePlaceHolder(type: .history)
refreshControl!.attributedTitle = NSAttributedString(string: "刷新数据中")
networkManager.getHistoryBook()
{ (response, errorInfo, books) in
if response == .success {
self.historyBookList = books
self.historyBookList.sort{ $0.returnDateTimeInterval > $1.returnDateTimeInterval }
self.tableView.reloadData()
if books.isEmpty {
self.delegate?.showPlaceHolder(message: "还没有借阅过书籍噢", for: .history)
}else{
self.delegate?.hidePlaceHolder(type: .history)
}
}else {
print(errorInfo?.errorDescription ?? response.rawValue)
self.HUD.show(message: errorInfo?.errorDescription ?? response.rawValue, time: 2)
self.delegate?.showPlaceHolder(message: "出错啦,下拉刷新一下吧?", for: .history)
}
self.refreshControl!.endRefreshing()
self.refreshControl!.attributedTitle = NSAttributedString(string: "下拉刷新数据")
}
}

Related

Refresh Control is not refreshing tableView properly

I have set up a refresh control but its not working, I did try to reloadData() in tableView , ill provide my code if there is a mistake :(
Its not reloading nothing in tableView
#objc private func refreshListData(_ sender: Any) {
self.monitorimiTableView.reloadData()
self.pullControl.endRefreshing()
}
override func viewDidLoad() {
super.viewDidLoad()
pullControl.bounds = CGRect(x: 0, y: 50, width: pullControl.bounds.size.width, height: pullControl.bounds.size.height)
pullControl.attributedTitle = NSAttributedString(string: "")
pullControl.addTarget(self, action: #selector(refreshListData(_:)), for: .valueChanged)
}
if #available(iOS 10.0, *) {
tableView.refreshControl = pullControl
} else {
tableView.addSubview(pullControl)
}
let refreshControl = UIRefreshControl()
override func viewDidLoad() {
super.viewDidLoad()
refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh")
refreshControl.addTarget(self, action: #selector(self.refresh(_:)), for: .valueChanged)
tableView.addSubview(refreshControl) // not required when using UITableViewController
}
#objc func refresh(_ sender: AnyObject) {
// Code to refresh table view
refreshControl.endRefreshing()
}

Pull to refresh and activity indicator on a view

I've a VC containing Table View. I've implemented pull to refresh on table view and activity indicator on view. On pull to refresh table view flickers as it looks like it has finished refreshing and reloads while I pull down and keep holding the table view. I'm not sure where it's going wrong. Following is my code. How to I implement it correctly?
class MyViewController: CustomVC {
override func viewDidLoad() {
super.viewDidLoad()
self.addRefreshControl(to: tableView)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
self.view.activityStartAnimating()
self.tableView.isHidden = true
loadContent(isRefresh: false)
}
private func loadContent(isRefresh: Bool) {
fetchContent() { (result, error) in
// ....
if isRefresh {
self.refreshControl.endRefreshing()
} else {
self.view.activityStopAnimating()
}
// ...
self.tableView.reloadData()
self.tableView.isHidden = false
}
}
// Pull to refresh
override func fetchDataForRefresh() {
loadContent(isRefresh: true)
}
}
Custom VC class
class CustomVC: UIViewController {
lazy var refreshControl: UIRefreshControl = {
let refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(refresh(_:)), for: UIControl.Event.valueChanged)
refreshControl.transform = CGAffineTransform(scaleX: 0.87, y: 0.87)
return refreshControl
}()
override func viewDidLoad() {
super.viewDidLoad()
}
func addRefreshControl(to tableView: UITableView) {
if #available(iOS 10.0, *) {
tableView.refreshControl = refreshControl
} else {
tableView.addSubview(refreshControl)
}
tableView.indicatorStyle = .white
}
#objc func refresh(_ refreshControl: UIRefreshControl) {
fetchDataForRefresh()
}
func fetchDataForRefresh() {
}
}
Fetch Content
func fetchContent() {
// .....
DispatchQueue.main.async {
completed(resultData,nil)
return
}
//....
}
Try this technique
func setupRefreshControl() {
refreshControl = UIRefreshControl()
refreshControl?.addTarget(self, action: #selector(refreshData), for: .valueChanged)
tableView?.refreshControl = refreshControl
}
When you finished fetching your data:
DispatchQueue.main.async {
self.refreshControl?.perform(#selector(UIRefreshControl.endRefreshing), with: nil, afterDelay: 0)
self.tableView.reloadData()
}
Please note I have access to refreshControl because I'm inside a UITableViewController but you can easily add it in a UIViewController as well.
Remove the if refresh else ... from your code and put your reload your UITableView and endRefreshing on the main thread as I mentioned above

Interaction between DUXPreFlightStatusWidget and DUXPreflightChecklistController is not working as advertised

According to https://developer.dji.com/api-reference/ios-uilib-api/Widgets/PreFlightStatusWidget.html:
"Tapping on status text will toggle between show and hide DUXPreflightChecklistController."
When I tap on the status text in the widget, the DUXPreflightChecklistController is not shown. Also, if I manually show the DUXPreflightChecklistController, there is a close button in the top right corner of the panel but tapping it does not hide the panel.
What is the proper way to configure this panel?
I'm using DJISDK 4.7.1 and DJIUXSDK 4.7.1 with Swift and iOS 12/xCode 10.0.
To provide a bit more detail, I do not want to use the Default Layout but I am using DUXStatusBarViewController. That is embedded in a UIView across the top of my app. I cannot find any properties for that controller that would allow me to hook it up to my instance of DUXPreflightChecklistController, which is also embedded in a UIView.
For: DUXPreflightChecklistController
I'd just solved that
var preflightChecklistController: DUXPreflightChecklistController!
weak var preFlightTableView: UITableView!
private var compassItemIndex: Int = -1
private var storageItemIndex: Int = -1
override func viewDidLoad() {
super.viewDidLoad()
preflightChecklistController = DUXPreflightChecklistController()
addChild(preflightChecklistController)
}
func renderChecklist() {
if let checklistVC = preflightChecklistController {
for subview in checklistVC.view.subviews {
if subview.isKind(of: UITableView.self) {
if let tableView = subview as? UITableView {
self.view.addSubview(tableView)
preFlightTableView = tableView
}
}
}
guard let checklistManager = checklistVC.checklistManager else { return }
let itemList = checklistManager.preFlightChecklistItems
for (index, item) in itemList.enumerated() {
if let _ = item as? DUXStorageCapacityChecklistItem {
storageItemIndex = index
}
if let _ = item as? DUXCompassChecklistItem {
compassItemIndex = index
}
}
preFlightTableView.reloadData()
checklistManager.startCheckingList()
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
renderChecklist()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
guard preFlightTableView != nil else { return }
if let compassCell = preFlightTableView.cellForRow(at: IndexPath(item: compassItemIndex, section: 0)) {
for view in compassCell.subviews {
if let button = view as? UIButton, button.titleLabel?.text == "Calibrate" {
button.addTarget(self, action: #selector(doActionForSpecifiedBTN(sender:)), for: .touchUpInside)
break
}
}
}
if let storageCell = preFlightTableView.cellForRow(at: IndexPath(item: storageItemIndex, section: 0)) {
for view in storageCell.subviews {
if let button = view as? UIButton, button.titleLabel?.text == "Format" {
button.addTarget(self, action: #selector(doActionForSpecifiedBTN(sender:)), for: .touchUpInside)
break
}
}
}
}
#objc func doActionForSpecifiedBTN(sender: UIButton) {
guard let btnTitle = sender.titleLabel else { return }
switch btnTitle.text {
case "Calibrate":
// your func goes here
case "Format":
// your func goes here
default:
break
}
}

Swift: Pull to refresh is too sensitive

am not too sure if anyone has encountered this issue, but it seems that my refreshControl is too sensitive. In my implementation, I attempt to do a pull to refresh and the code executes even before I see the refreshControl spinning.
Is there something wrong I'm doing?
My implementation so far.
//At initiation
lazy var refreshControl: UIRefreshControl = {
let rc = UIRefreshControl()
rc.tintColor = .white
rc.addTarget(self, action: #selector(refreshControlDidRefresh), for: .valueChanged)
return rc
}()
//At viewDidLoad(), I call a function setupViews()
func setupViews() {
view.backgroundColor = .white
view.addSubview(tableView)
tableView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
tableView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor).isActive = true
tableView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor).isActive = true
tableView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true
tableView.register(GossipsTableViewCell.self, forCellReuseIdentifier: "gossipCell")
tableView.tableHeaderView = emptyTableViewHeader()
tableView.refreshControl = refreshControl
}
#objc func refreshControlDidRefresh() {
DispatchQueue.main.async {
self.gossips.removeAll()
self.tableView.reloadData()
}
getData()
}
func getData() {
FirebaseClient.shared.fetchAllGossips { (results, error) in
if let error = error {
print(error.localizedDescription)
} else if let results = results {
self.gossips = results.sorted(by: { (gossip1, gossip2) -> Bool in
guard
let gossip1Timestamp = gossip1.timestamp,
let gossip2Timestamp = gossip2.timestamp else {
return false
}
return gossip1Timestamp > gossip2Timestamp
})
self.filterGossips()
DispatchQueue.main.async {
if self.refreshControl.isRefreshing {
self.refreshControl.endRefreshing()
}
if JustHUD.shared.isActive {
JustHUD.shared.hide()
}
var indexPaths = [IndexPath]()
for (index, _) in self.gossips.enumerated() {
let indexPath = IndexPath(row: index, section: 0)
indexPaths.append(indexPath)
}
self.tableView.insertRows(at: indexPaths, with: .automatic)
self.segmentedControl.isUserInteractionEnabled = true
}
}
}
}
You may see the results here. As I attempt to pull down, the refresh gets executed even before I start to see the refreshControl being drawn. Is there anything I'm missing out?
You are doing everything correctly, this is the default behaviour of pull to refresh control. If you want it to act differently, try a 3rd-part solution or remove the control and implement your own logic in scrollViewDidScroll.

How to use pull to refresh in Swift?

I am building an RSS reader using swift and need to implement pull to reload functionality.
Here is how i am trying to do it.
class FirstViewController: UIViewController,
UITableViewDelegate, UITableViewDataSource {
#IBOutlet var refresh: UIScreenEdgePanGestureRecognizer
#IBOutlet var newsCollect: UITableView
var activityIndicator:UIActivityIndicatorView? = nil
override func viewDidLoad() {
super.viewDidLoad()
self.newsCollect.scrollEnabled = true
// Do any additional setup after loading the view, typically from a nib.
if nCollect.news.count <= 2{
self.collectNews()
}
else{
self.removeActivityIndicator()
}
view.addGestureRecognizer(refresh)
}
#IBAction func reload(sender: UIScreenEdgePanGestureRecognizer) {
nCollect.news = News[]()
return newsCollect.reloadData()
}
I am getting :
Property 'self.refresh' not initialized at super.init call
Please help me to understand the behaviour of Gesture recognisers. A working sample code will be a great help.
Thanks.
Pull to refresh is built in iOS. You could do this in swift like
let refreshControl = UIRefreshControl()
override func viewDidLoad() {
super.viewDidLoad()
refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh")
refreshControl.addTarget(self, action: #selector(self.refresh(_:)), for: .valueChanged)
tableView.addSubview(refreshControl) // not required when using UITableViewController
}
#objc func refresh(_ sender: AnyObject) {
// Code to refresh table view
}
At some point you could end refreshing.
refreshControl.endRefreshing()
A solution with storyboard and Swift:
Open your .storyboard file, select a TableViewController in your storyboard and "Enable" the Table View Controller: Refreshing feature in the Utilities.
Open the associated UITableViewController class and add the following Swift 5 line into the viewDidLoad method.
self.refreshControl?.addTarget(self, action: #selector(refresh), for: UIControl.Event.valueChanged)
Add the following method above the viewDidLoad method
func refresh(sender:AnyObject)
{
// Updating your data here...
self.tableView.reloadData()
self.refreshControl?.endRefreshing()
}
UIRefreshControl is directly supported in each of UICollectionView, UITableView and UIScrollView (requires iOS 10+)!
Each one of these views has a refreshControl instance property, which means that there is no longer a need to add it as a subview in your scroll view, all you have to do is:
#IBOutlet weak var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
let refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(doSomething), for: .valueChanged)
// this is the replacement of implementing: "collectionView.addSubview(refreshControl)"
collectionView.refreshControl = refreshControl
}
#objc func doSomething(refreshControl: UIRefreshControl) {
print("Hello World!")
// somewhere in your code you might need to call:
refreshControl.endRefreshing()
}
Personally, I find it more natural to treat it as a property for scroll view more than adding it as a subview, especially because the only appropriate view to be as a superview for a UIRefreshControl is a scrollview, i.e the functionality of using UIRefreshControl is only useful when working with a scroll view; That's why this approach should be more obvious to set up the refresh control view.
However, you still have the option of using the addSubview based on the iOS version:
if #available(iOS 10.0, *) {
collectionView.refreshControl = refreshControl
} else {
collectionView.addSubview(refreshControl)
}
Swift 4
var refreshControl: UIRefreshControl!
override func viewDidLoad() {
super.viewDidLoad()
refreshControl = UIRefreshControl()
refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh")
refreshControl.addTarget(self, action: #selector(refresh), for: .valueChanged)
tableView.addSubview(refreshControl)
}
#objc func refresh(_ sender: Any) {
// your code to reload tableView
}
And you could stop refreshing with:
refreshControl.endRefreshing()
Swift 5
private var pullControl = UIRefreshControl()
pullControl.attributedTitle = NSAttributedString(string: "Pull to refresh")
pullControl.addTarget(self, action: #selector(refreshListData(_:)), for: .valueChanged)
if #available(iOS 10.0, *) {
tableView.refreshControl = pullControl
} else {
tableView.addSubview(pullControl)
}
// Actions
#objc private func refreshListData(_ sender: Any) {
self.pullControl.endRefreshing() // You can stop after API Call
// Call API
}
In Swift use this,
If you wants to have pull to refresh in WebView,
So try this code:
override func viewDidLoad() {
super.viewDidLoad()
addPullToRefreshToWebView()
}
func addPullToRefreshToWebView(){
var refreshController:UIRefreshControl = UIRefreshControl()
refreshController.bounds = CGRectMake(0, 50, refreshController.bounds.size.width, refreshController.bounds.size.height) // Change position of refresh view
refreshController.addTarget(self, action: Selector("refreshWebView:"), forControlEvents: UIControlEvents.ValueChanged)
refreshController.attributedTitle = NSAttributedString(string: "Pull down to refresh...")
YourWebView.scrollView.addSubview(refreshController)
}
func refreshWebView(refresh:UIRefreshControl){
YourWebView.reload()
refresh.endRefreshing()
}
Anhil's answer helped me a lot.
However, after experimenting further I noticed that the solution suggested sometimes causes a not-so-pretty UI glitch.
Instead, going for this approach* did the trick for me.
*Swift 2.1
//Create an instance of a UITableViewController. This will host your UITableView.
private let tableViewController = UITableViewController()
//Add tableViewController as a childViewController and set its tableView property to your UITableView.
self.addChildViewController(self.tableViewController)
self.tableViewController.tableView = self.tableView
self.refreshControl.addTarget(self, action: "refreshData:", forControlEvents: .ValueChanged)
self.tableViewController.refreshControl = self.refreshControl
Details
Xcode Version 10.3 (10G8), Swift 5
Features
Ability to make "pull to refresh" programmatically
Protection from multi- "pull to refresh" events
Ability to continue animating of the activity indicator when view controller switched (e.g. in case of TabController)
Solution
import UIKit
class RefreshControl: UIRefreshControl {
private weak var actionTarget: AnyObject?
private var actionSelector: Selector?
override init() { super.init() }
convenience init(actionTarget: AnyObject?, actionSelector: Selector) {
self.init()
self.actionTarget = actionTarget
self.actionSelector = actionSelector
addTarget()
}
private func addTarget() {
guard let actionTarget = actionTarget, let actionSelector = actionSelector else { return }
addTarget(actionTarget, action: actionSelector, for: .valueChanged)
}
required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) }
func endRefreshing(deadline: DispatchTime? = nil) {
guard let deadline = deadline else { endRefreshing(); return }
DispatchQueue.global(qos: .default).asyncAfter(deadline: deadline) { [weak self] in
DispatchQueue.main.async { self?.endRefreshing() }
}
}
func refreshActivityIndicatorView() {
guard let selector = actionSelector else { return }
let _isRefreshing = isRefreshing
removeTarget(actionTarget, action: selector, for: .valueChanged)
endRefreshing()
if _isRefreshing { beginRefreshing() }
addTarget()
}
func generateRefreshEvent() {
beginRefreshing()
sendActions(for: .valueChanged)
}
}
public extension UIScrollView {
private var _refreshControl: RefreshControl? { return refreshControl as? RefreshControl }
func addRefreshControll(actionTarget: AnyObject?, action: Selector, replaceIfExist: Bool = false) {
if !replaceIfExist && refreshControl != nil { return }
refreshControl = RefreshControl(actionTarget: actionTarget, actionSelector: action)
}
func scrollToTopAndShowRunningRefreshControl(changeContentOffsetWithAnimation: Bool = false) {
_refreshControl?.refreshActivityIndicatorView()
guard let refreshControl = refreshControl,
contentOffset.y != -refreshControl.frame.height else { return }
setContentOffset(CGPoint(x: 0, y: -refreshControl.frame.height), animated: changeContentOffsetWithAnimation)
}
private var canStartRefreshing: Bool {
guard let refreshControl = refreshControl, !refreshControl.isRefreshing else { return false }
return true
}
func startRefreshing() {
guard canStartRefreshing else { return }
_refreshControl?.generateRefreshEvent()
}
func pullAndRefresh() {
guard canStartRefreshing else { return }
scrollToTopAndShowRunningRefreshControl(changeContentOffsetWithAnimation: true)
_refreshControl?.generateRefreshEvent()
}
func endRefreshing(deadline: DispatchTime? = nil) { _refreshControl?.endRefreshing(deadline: deadline) }
}
Usage
// Add refresh control to UICollectionView / UITableView / UIScrollView
private func setupTableView() {
let tableView = UITableView()
// ...
tableView.addRefreshControll(actionTarget: self, action: #selector(refreshData))
}
#objc func refreshData(_ refreshControl: UIRefreshControl) {
tableView?.endRefreshing(deadline: .now() + .seconds(3))
}
// Stop refreshing in UICollectionView / UITableView / UIScrollView
tableView.endRefreshing()
// Simulate pull to refresh in UICollectionView / UITableView / UIScrollView
tableView.pullAndRefresh()
Full Sample
Do not forget to add the solution code here
import UIKit
class ViewController: UIViewController {
private weak var tableView: UITableView?
override func viewDidLoad() {
super.viewDidLoad()
setupTableView()
}
private func setupTableView() {
let tableView = UITableView()
view.addSubview(tableView)
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
tableView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
tableView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
tableView.dataSource = self
tableView.delegate = self
tableView.addRefreshControll(actionTarget: self, action: #selector(refreshData))
self.tableView = tableView
}
}
extension ViewController {
#objc func refreshData(_ refreshControl: UIRefreshControl) {
print("refreshing")
tableView?.endRefreshing(deadline: .now() + .seconds(3))
}
}
extension ViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int { return 1 }
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 20 }
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
cell.textLabel?.text = "\(indexPath)"
return cell
}
}
extension ViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.pullAndRefresh()
}
}
What the error is telling you, is that refresh isn't initialized. Note that you chose to make refresh not optional, which in Swift means that it has to have a value before you call super.init (or it's implicitly called, which seems to be your case). Either make refresh optional (probably what you want) or initialize it in some way.
I would suggest reading the Swift introductory documentation again, which covers this in great length.
One last thing, not part of the answer, as pointed out by #Anil, there is a built in pull to refresh control in iOS called UIRefresControl, which might be something worth looking into.
I built a RSS feed app in which I have a Pull To refresh feature that originally had some of the problems listed above.
But to add to the users answers above, I was looking everywhere for my use case and could not find it. I was downloading data from the web (RSSFeed) and I wanted to pull down on my tableView of stories to refresh.
What is mentioned above cover the right areas but with some of the problems people are having, here is what I did and it works a treat:
I took #Blankarsch 's approach and went to my main.storyboard and select the table view to use refresh, then what wasn't mentioned is creating IBOutlet and IBAction to use the refresh efficiently
//Created from main.storyboard cntrl+drag refresh from left scene to assistant editor
#IBOutlet weak var refreshButton: UIRefreshControl
override func viewDidLoad() {
......
......
//Include your code
......
......
//Is the function called below, make sure to put this in your viewDidLoad
//method or not data will be visible when running the app
getFeedData()
}
//Function the gets my data/parse my data from the web (if you havnt already put this in a similar function)
//remembering it returns nothing, hence return type is "-> Void"
func getFeedData() -> Void{
.....
.....
}
//From main.storyboard cntrl+drag to assistant editor and this time create an action instead of outlet and
//make sure arguments are set to none and note sender
#IBAction func refresh() {
//getting our data by calling the function which gets our data/parse our data
getFeedData()
//note: refreshControl doesnt need to be declared it is already initailized. Got to love xcode
refreshControl?.endRefreshing()
}
Hope this helps anyone in same situation as me
func pullToRefresh(){
let refresh = UIRefreshControl()
refresh.addTarget(self, action: #selector(handleTopRefresh(_:)), for: .valueChanged )
refresh.tintColor = UIColor.appBlack
self.tblAddressBook.addSubview(refresh)
}
#objc func handleTopRefresh(_ sender:UIRefreshControl){
self.callAddressBookListApi(isLoaderRequired: false)
sender.endRefreshing()
}
I suggest to make an Extension of pull To Refresh to use in every class.
1) Make an empty swift file : File - New - File - Swift File.
2) Add the Following
// AppExtensions.swift
import Foundation
import UIKit
var tableRefreshControl:UIRefreshControl = UIRefreshControl()
//MARK:- VIEWCONTROLLER EXTENSION METHODS
public extension UIViewController
{
func makePullToRefreshToTableView(tableName: UITableView,triggerToMethodName: String){
tableRefreshControl.attributedTitle = NSAttributedString(string: "TEST: Pull to refresh")
tableRefreshControl.backgroundColor = UIColor.whiteColor()
tableRefreshControl.addTarget(self, action: Selector(triggerToMethodName), forControlEvents: UIControlEvents.ValueChanged)
tableName.addSubview(tableRefreshControl)
}
func makePullToRefreshEndRefreshing (tableName: String)
{
tableRefreshControl.endRefreshing()
//additional codes
}
}
3) In Your View Controller call these methods as :
override func viewWillAppear(animated: Bool) {
self.makePullToRefreshToTableView(bidderListTable, triggerToMethodName: "pullToRefreshBidderTable")
}
4) At some point you wanted to end refreshing:
func pullToRefreshBidderTable() {
self.makePullToRefreshEndRefreshing("bidderListTable")
//Code What to do here.
}
OR
self.makePullToRefreshEndRefreshing("bidderListTable")
For the pull to refresh i am using
DGElasticPullToRefresh
https://github.com/gontovnik/DGElasticPullToRefresh
Installation
pod 'DGElasticPullToRefresh'
import DGElasticPullToRefresh
and put this function into your swift file and call this funtion from your
override func viewWillAppear(_ animated: Bool)
func Refresher() {
let loadingView = DGElasticPullToRefreshLoadingViewCircle()
loadingView.tintColor = UIColor(red: 255.0/255.0, green: 255.0/255.0, blue: 255.0/255.0, alpha: 1.0)
self.table.dg_addPullToRefreshWithActionHandler({ [weak self] () -> Void in
//Completion block you can perfrom your code here.
print("Stack Overflow")
self?.table.dg_stopLoading()
}, loadingView: loadingView)
self.table.dg_setPullToRefreshFillColor(UIColor(red: 255.0/255.0, green: 57.0/255.0, blue: 66.0/255.0, alpha: 1))
self.table.dg_setPullToRefreshBackgroundColor(self.table.backgroundColor!)
}
And dont forget to remove reference while view will get dissapear
to remove pull to refresh put this code in to your
override func viewDidDisappear(_ animated: Bool)
override func viewDidDisappear(_ animated: Bool) {
table.dg_removePullToRefresh()
}
And it will looks like
Happy coding :)
You can achieve this by using few lines of code. So why you are going to stuck in third party library or UI.
Pull to refresh is built in iOS. You could do this in swift like
var pullControl = UIRefreshControl()
override func viewDidLoad() {
super.viewDidLoad()
pullControl.attributedTitle = NSAttributedString(string: "Pull to refresh")
pullControl.addTarget(self, action: #selector(pulledRefreshControl(_:)), for: UIControl.Event.valueChanged)
tableView.addSubview(pullControl) // not required when using UITableViewController
}
#objc func pulledRefreshControl(sender:AnyObject) {
// Code to refresh table view
}
you can use this subclass of tableView:
import UIKit
protocol PullToRefreshTableViewDelegate : class {
func tableViewDidStartRefreshing(tableView: PullToRefreshTableView)
}
class PullToRefreshTableView: UITableView {
#IBOutlet weak var pullToRefreshDelegate: AnyObject?
private var refreshControl: UIRefreshControl!
private var isFirstLoad = true
override func willMoveToSuperview(newSuperview: UIView?) {
super.willMoveToSuperview(newSuperview)
if (isFirstLoad) {
addRefreshControl()
isFirstLoad = false
}
}
private func addRefreshControl() {
refreshControl = UIRefreshControl()
refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh")
refreshControl.addTarget(self, action: "refresh", forControlEvents: .ValueChanged)
self.addSubview(refreshControl)
}
#objc private func refresh() {
(pullToRefreshDelegate as? PullToRefreshTableViewDelegate)?.tableViewDidStartRefreshing(self)
}
func endRefreshing() {
refreshControl.endRefreshing()
}
}
1 - in interface builder change the class of your tableView to PullToRefreshTableView or create a PullToRefreshTableView programmatically
2 - implement the PullToRefreshTableViewDelegate in your view controller
3 - tableViewDidStartRefreshing(tableView: PullToRefreshTableView) will be called in your view controller when the table view starts refreshing
4 - call yourTableView.endRefreshing() to finish the refreshing
This is how I made it work using Xcode 7.2 which I think is a major bug. I'm using it inside my UITableViewController inside my viewWillAppear
refreshControl = UIRefreshControl()
refreshControl!.addTarget(self, action: "configureMessages", forControlEvents: .ValueChanged)
refreshControl!.beginRefreshing()
configureMessages()
func configureMessages() {
// configuring messages logic here
self.refreshControl!.endRefreshing()
}
As you can see, I literally have to call the configureMessage() method after setting up my UIRefreshControl then after that, subsequent refreshes will work fine.
For 2023, this simple
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
your data source = latest ...
table.reloadData()
table.refreshControl = UIRefreshControl()
table.refreshControl?.addTarget(self,
action: #selector(pulldown), for: .valueChanged)
table.refreshControl?.tintColor = .clear
}
#objc func pulldown() {
your data source = latest ...
table.reloadData()
DispatchQueue.main.async { self.table.refreshControl?.endRefreshing() }
}
Very often, you don't want the "spinner". This line is the easiest way to hide the spinner:
table.refreshControl?.tintColor = .clear
That's it.
If (for some obscure reason) you truly want to subclass UIRefreshControl, there's an excellent recent answer here that shows how to do that.
Others Answers Are Correct But for More Detail check this Post Pull to Refresh
Enable refreshing in Storyboard
When you’re working with a UITableViewController, the solution is fairly simple: First, Select the table view controller in your storyboard, open the attributes inspector, and enable refreshing:
A UITableViewController comes outfitted with a reference to a UIRefreshControl out of the box. You simply need to wire up a few things to initiate and complete the refresh when the user pulls down.
Override viewDidLoad()
In your override of viewDidLoad(), add a target to handle the refresh as follows:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.refreshControl?.addTarget(self, action: "handleRefresh:", forControlEvents: UIControlEvents.ValueChanged)
}
Since I’ve specified “handleRefresh:” (note the colon!) as the
action argument, I need to define a function in this
UITableViewController class with the same name. Additionally, the
function should take one argument
We’d like this action to be called for the UIControlEvent called
ValueChanged
Don't forget to call refreshControl.endRefreshing()
For more information Please go to mention Link and all credit goes to that post
Due to less customisability, code duplication and bugs which come with pull to refresh control, I created a library PullToRefreshDSL which uses DSL pattern just like SnapKit
// You only have to add the callback, rest is taken care of
tableView.ptr.headerCallback = { [weak self] in // weakify self to avoid strong reference
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(2)) { // your network call
self?.tableView.ptr.isLoadingHeader = false // setting false will hide the view
}
}
You only have to add magical keyword ptr after any UIScrollView subclass i.e. UITableView/UICollectionView
You dont have to download the library, you can explore and modify the source code, I am just pointing towards a possible implementation of pull to refresh for iOS

Resources