Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pull to refresh in Swift

Tags:

ios

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()
{
    super.viewDidLoad()

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

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?

like image 912
Reece Kenney Avatar asked Mar 19 '23 08:03

Reece Kenney


1 Answers

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)
tableView.addSubview(refreshControl!)
like image 101
rob mayoff Avatar answered Apr 06 '23 07:04

rob mayoff