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()
}
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
}
}
Answer for swift 5.0
override func viewWillAppear(_ animated: Bool) {
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
With this code it worked for me.
来源:https://stackoverflow.com/questions/33332861/how-to-refresh-a-tableview-on-click-tabbar-item-swift