Reece Kenney Reece Kenney -4 years ago 222
iOS Question

Pull to refresh in Swift

I'm trying to implement pull to refresh in my table view app. I've been looking around at people's examples and I've gathered that this is pretty much the gist of it:

var refreshControl:UIRefreshControl!

override func viewDidLoad()

self.refreshControl = UIRefreshControl()
self.refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh")
self.refreshControl.addTarget(self, action: "refresh:", forControlEvents: UIControlEvents.ValueChanged)

func refresh(sender:AnyObject)
// Code to refresh table view

However the only examples I can find are from a while ago and I know the language has changed a lot since then! When I try to use the code above, I get the following error next to my declaration of refreshControl:

Cannot override with a stored property 'refresh control'

My first thought before reading other examples is that I would have to declare the variable like so:

var refreshControl:UIRefreshControl = UIRefreshControl()

Like I did with some other variables but I guess not.
Any ideas what the issue is?

Answer Source

I gather your class inherits UITableViewController. UITableViewController already declares the refreshControl property like this:

@availability(iOS, introduced=6.0)
var refreshControl: UIRefreshControl?

You don't need to override it. Just get rid of your var declaration and assign to the inherited property.

Since the inherited property is Optional, you need to use a ? or ! to unwrap it:

refreshControl = UIRefreshControl()
refreshControl!.attributedTitle = NSAttributedString(string: "Pull to refresh")
refreshControl!.addTarget(self, action: "refresh:", forControlEvents: UIControlEvents.ValueChanged)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download