Refresh Control on top of tableview when I go back to view controller

jplozano picture jplozano · Jul 4, 2016 · Viewed 10.2k times · Source

For some reason, the first time the view controller is loaded, the refresh control behaves as expected (that it, showing under tableview when swipe down). The problem is when I tap on another tab, and then go back to the view controller, the refresh control does not fade in anymore and is visible on top of the tableview.

When I go back to view controller

This is part of the code:

class CoreTableViewController : UIViewController, UITableViewDataSource, UITableViewDelegate {

var tableView:UITableView!
var tableData:Array<AnyObject> = []
var dataFetched:Bool = false
var refreshControl:UIRefreshControl?

override func viewDidLoad() {
    super.viewDidLoad()

    self.edgesForExtendedLayout = UIRectEdge.None;

    self.tableView = self.assignTableView()
    self.tableView.delegate = self
    self.tableView.dataSource = self
    self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell")
    self.tableView.separatorStyle = UITableViewCellSeparatorStyle.None;

    if self.enableRefresher() {
        self.setRefreshControl()
    }
}

func enableRefresher() -> Bool {
    return true
}

func fetchData(cleanFirst:Bool = false) {
    // Fetch data.
}

func refresh() {
    self.fetchData(true)
    self.refreshControl!.endRefreshing()
}

func setRefreshControl() {
    self.refreshControl = UIRefreshControl()
    //self.refreshControl!.attributedTitle = NSAttributedString(string: "Actualizar")
    self.refreshControl!.addTarget(self, action: #selector(CoreTableViewController.refresh), forControlEvents: UIControlEvents.ValueChanged)
    self.tableView.addSubview(refreshControl!)
}

}

Any thoughts?

Answer

jplozano picture jplozano · Jul 8, 2016

I found the fix here: https://stackoverflow.com/a/29088409/209200

Instead of self.tableView.addSubview(refreshControl!), it should be self.tableView.insertSubview(refreshControl!, atIndex: 0).

That was causing the refres control to appear over the tableview.