Custom Pull-To-RefreshView: Swift 4

Overview

Hello Everyone. Hope you doing well and having a nice day. In this article, we are going to focus on creating the custom pull to refresh control. It was introduced several years ago, created by popular Twitter Client Loren Brichter. The idea is very simple just pull down to refresh the content of a UITableView or UICollectionView, even UIScrollView too. Lots of application use pull to refresh with cool and nice animation, especially in Snapchat.

So I decided to create my own custom pull to refresh (and sharing is caring right). I love to do complex thing in simple way so everyone can understand easily even for beginner and this one is really simple, believe me! In iOS 6 Apple made pull to refresh very easy with UIRefreshControl.

The following video shows our article’s demonstration.

Let’s get started with the fun part. I’m assuming that you are familiar with project setup.

Designing

Command + N.
custom-pull-image1

Feel free in naming the file and saving as per your choice.

After creating xib, first in an attribute inspector, change size to freedom. It will allow to resize the xib easily for designing.

custom-pull-image2

For article purpose, I’ve designed Xib as below:

custom-pull-image3

That’s it for designing. We have completed our 50% of work here now let’s jump to ViewController.swift file.

Coding

We are going to declare couple of variables.

var refreshView: RefreshView!
. “RefreshView” is class name which I have given to above xib. Variable is for not to initialize but further down we are going to do it in getRefereshView() method.

Below is the compute variable of UIRefreshControl, along with clear background, tintcolor and adding the target method of it.

Now we need the xib from the Bundle. The Bundle will return an Array of nib as Any. We need to downcast with the first object with using if statement as RefreshView. In the below method refreshView frame is given according to tableViewRefreshControl and lastly adding refreshView as addSubview of tableViewRefreshControl.

Targeting method refreshTableView will be called when user perform pull to refresh. In this project and particularly for the article purpose I’ve started animation of company logo that will last for 5 seconds and then tableView will be back to normal state.

At last, prepareUI method needs to be added in viewDidLoad.

Don’t forget to add tableView and its delegate and dataSource. Now run the code. See the magic of your work.

Oh Yes!. if you wondering the animation of below highlighting the company logo. Please take a look at code.

custom-pull-image5

mm

Kevin Shah iOS Developer

I am Kevin Shah, iOS Developer at Yudiz Solutions Pvt. Ltd. - a leading iPhone App development company. Continuously discover, evaluate and implement new technologies to maximize development efficiency.

Leave a Reply

Top