简体   繁体   中英

How to refresh a tableView on click tabBar item Swift?

I have a tableView into a viewController on tab Bar. When I click into tabBar item the tableView isn't refreshing. But I have the viewWillAppear function:

 override func viewWillAppear(animated: Bool) {
    dispatch_async(dispatch_get_main_queue(), { () -> Void in
        self.tableView.reloadData()
    })
}

I'm trying call this function with tab bar delegate, but not works:

 func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) {
     dispatch_async(dispatch_get_main_queue(), { () -> Void in
        self.tableView.reloadData()
    })
 }

Why not reload?

Thanks!

You do not need to involve the tab bar controller in this. To do so would be overkill. You'll create confusing code that somebody will want to rip out later. Updating the table view in viewWillAppear(_:) is almost always the best approach.

If everything is set up properly, your view controller's viewWillAppear(_:) method will get called each time the user selects that tab and your view becomes visible. So if it's not getting called, you have a problem somewhere in the design of your tab bar and its view controllers.

Create a new project and select the Tabbed Application template. Open the SecondViewController file and add a viewWillAppear(_:) method. Add a breakpoint there. You'll see it's called every time you switch to the second tab.

Some other thoughts...

You'll notice in the viewWillAppear(_:) documentation that it says you must always call super. You're not. You should. But this is unrelated to your problem.

Also, there's no need to switch to the main queue. viewWillAppear(_:) will always be called on the main queue.

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    tableView.reloadData()
}

Answer for swift 5.0

Reload UITableView in main thread and then check. I hope this will work for you.

override func viewWillAppear(_ animated: Bool) {
    DispatchQueue.main.async {  
        self.tableView.reloadData()
    }
}

You can find the answer here: open viewcontroller from tab like in instagram camera page on IOS

Basically, you need to create a controller which inherits from UITabBarController and set it in the Storyboard to the custom class of your tabBarView.

Then set Tags to each Tab via the Storyboard.

Afterwards you can use the delegate method to call an action if a specific tab was clicked.

The delegate method should look like this:

override func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) {
    switch item.tag{
    case 1: //code here
         break
    default: break
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM