Skip to main content

How To Use Custom UIRefreshControl in Swift

UIRefreshControl in Swift

Custom UIRefreshControl in swift

Custom UIRefreshControl : 

 UIRefreshControl is provided in iOS that allowed user to drag UITableView to refresh the contents of UITableVIew. This is most common approach used in mobile apps to allow user to forcefully refresh the contents of list or UITable. In this tutorial, we will learn how to create a custom UIRefreshControl in swift rather than using the default standard UIRefreshControl provided by iOS having an UIActivityIndicatorView.

Steps to create custom UIRefreshControl in swift:

Step 1: Create a single view application template project, and open Main.storyboard file

Step 2: Change view background color of  view to yellow and drag a UITableView on to the view of ViewController.

Adding UITableView on to the view  - custom UIRefreshcontrol swift
Step 3: Set constraints to UITableView as shown in the below picture, we set 0 distance from all 4 sides with respect to safe area layout.

Setting constraints to UITableView - custom UIRefreshControl swift

Step 4: Open ViewController.swift and create an IBOutlet for UITableView named as "tblList"

//
// ViewController.swift
// Custom-RefreshControl-swift-ios
//
// Created by iostutorialpoints on 12/05/18.
// Copyright © 2018 iostutorialpoints. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var tblList: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}


Step 5: Connect IBOutlet to UITableView in Main.storyboard

Connecting IBOutlet to UITableView - custom UIRefreshControl swift

Designing our custom UIRefreshControl

Step 6: In ViewController.swift, create a function named "addRefreshControl". In this function we will create UIRefreshControl and add it to our UITableView. But before this, we will design layout for our custom refresh control. For creating design for custom refresh control either press command+N or click on File menu of Xcode and then new file (shown in the image). Name the file as

"CustomRefreshView"

Creating new file for custom refresh control view

Selecting view file for our custom refresh control

Step 7: Open "CustomRefreshView.xib" and  made the changes as shown in the given below picture as per the steps written

Design user interface for custom refresh control

Use custom UIRefreshControl in UITableview

Step 8: At this point, we are done with designing interface for our custom refresh control. Now, it's time to write code for custom UIRefreshControl. Open ViewController.swift file and add the code as
shown in the given below code snippet

//
// ViewController.swift
// Custom-RefreshControl-swift-ios
//
// Created by iostutorialpoints.com on 12/05/18.
// Copyright © 2018 iostutorialpoints.com . All rights reserved.
//
import UIKit
class ViewController: UIViewController {

@IBOutlet weak var tblList: UITableView!
var refreshControl = UIRefreshControl()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
addRefreshControl()
}
func addRefreshControl() {
guard let customView = Bundle.main.loadNibNamed("CustomRefreshView", owner: nil, options: nil) else {
return
}
guard let refreshView = customView[0] as? UIView else {
return
}
refreshView.tag = 12052018
refreshView.frame = refreshControl.frame
refreshControl.addSubview(refreshView)
refreshControl.tintColor = UIColor.clear
refreshControl.backgroundColor = UIColor.clear
refreshControl.addTarget(self, action: #selector(refreshContents), for: .valueChanged)
if #available(iOS 10.0, *) {
tblList.refreshControl = refreshControl
} else {
tblList.addSubview(refreshControl)
}
}
@objc func refreshContents() {
self.perform(#selector(finishedRefreshing), with: nil, afterDelay: 3.0)
}

@objc func finishedRefreshing() {
refreshControl.endRefreshing()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

Let us go through the code we created in step by step

  1. We created an instance of UIRefreshControl and named it "refreshControl". 
  2. Created a function named "addRefreshControl" and called it in ViewDidLoad method.
  3. Inside "addRefreshControl" function, we check whether our app contains file named "CustomRefreshView" or not, if not then we returned from function and thus saving our app from getting crashed but no UIRefreshControl is added.
  4. We get view object from the file object, named here "customView"
  5. Given tag for view object, named "refreshView", and also set its frame equal to that of "refreshControl".
  6. Add "refreshView" as sub-view to "refreshControl". 
  7. Set background color and tint color of "refreshControl"to clear color.
  8. Add target to "refreshControl" so that we can detect when user pull down the UITableView for refreshing contents,
  9. Adding "refreshControl" to UITableView. If we are having iOS 10.0 or greater then UITableView has property refreshControl otherwise for lower version we will add "refreshControl" as subview to UITableView.
  10. Lastly we will implement our selectors.
  11. In order to stop refreshing, we need to call method "endRefreshing".

Changing UILable text when user pull down  UItableView

Step 9: To change text of UILable, when user pulls down UITableView, you can use he below code

@objc func refreshContents() {
let refreshView = refreshControl.viewWithTag(12052018)
for vw in (refreshView?.subviews)! {
if let titleLable = vw as? UILabel {
titleLable.text = "Refreshing contents"
}
}
self.perform(#selector(finishedRefreshing), with: nil, afterDelay: 3.0)
}
@objc func finishedRefreshing() {
refreshControl.endRefreshing()
let refreshView = refreshControl.viewWithTag(12052018)
for vw in (refreshView?.subviews)! {
if let titleLable = vw as? UILabel {
titleLable.text = "Pull down to refresh this list"
}
}
}
 
 

In the above code, we get "refreshView" form refreshControl object. Then we get UILabel from "refreshView", subview's. Lastly changed the text for UILabel.

Where to go from here:

In this tutorial, we learned how to create custom UIRefreshControl in swift and then add it to UITableView. You can do other stuffs too, like animating the UILabel or placing image instead of UILabel and animate it. To download the code, please click this link Custom-RefreshControl

Comments

Popular Posts

Reloading UITableView while Animating Scroll in iOS 11

Reloading UITableView while Animating Scroll Calling  reloadData  on  UITableView  may not be the most efficient way to update your cells, but sometimes it’s easier to ensure the data you are storing is in sync with what your  UITableView  is showing. In iOS 10  reloadData  could be called at any time and it would not affect the scrolling UI of  UITableView . However, in iOS 11 calling  reloadData  while your  UITableView  is animating scrolling causes the  UITableView  to stop its scroll animation and not complete. We noticed this is only true for scroll animations triggered via one of the  UITableView  methods (such as  scrollToRow(at:at:animated:) ) and not for scroll animations caused by user interaction. This can be an issue when server responses trigger a  reloadData  call since they can happen at any moment, possibly when scroll animation is occurring. Example of s...

What are the Alternatives of device UDID in iOS? - iOS7 / iOS 6 / iOS 5 – Get Device Unique Identifier UDID

Get Device Unique Identifier UDID Following code will help you to get the unique-device-identifier known as UDID. No matter what iOS user is using, you can get the UDID of the current iOS device by following code. - ( NSString *)UDID { NSString *uuidString = nil ; // get os version NSUInteger currentOSVersion = [[[[[UIDevice currentDevice ] systemVersion ] componentsSeparatedByString: @" . " ] objectAtIndex: 0 ] integerValue ]; if (currentOSVersion <= 5 ) { if ([[ NSUserDefaults standardUserDefaults ] valueForKey: @" udid " ]) { uuidString = [[ NSUserDefaults standardDefaults ] valueForKey: @" udid " ]; } else { CFUUIDRef uuidRef = CFUUIDCreate ( kCFAllocatorDefault ); uuidString = ( NSString *) CFBridgingRelease ( CFUUIDCreateString ( NULL ,uuidRef)); CFRelease (uuidRef); [[ NSUserDefaults standardUserDefaults ] setObject: uuidString ForKey: @" udid " ]; [[ NSUserDefaults standardUserDefaults ] synchro...

Xcode & Instruments: Measuring Launch time, CPU Usage, Memory Leaks, Energy Impact and Frame Rate

When you’re developing applications for modern mobile devices, it’s vital that you consider the performance footprint that it has on older devices and in less than ideal network conditions. Fortunately Apple provides several powerful tools that enable Engineers to measure, investigate and understand the different performance characteristics of an application running on an iOS device. Recently I spent some time with these tools working to better understand the performance characteristics of an eCommerce application and finding ways that we can optimise the experience for our users. We realised that applications that are increasingly performance intensive, consume excessive amounts of memory, drain battery life and feel uncomfortably slow are less likely to retain users. With the release of iOS 12.0 it’s easier than ever for users to find applications that are consuming the most of their device’s finite amount of resources. Users can now make informed decisions abou...