How to refresh a tableView on click tabBar item Swift?

独自空忆成欢 提交于 2019-12-03 21:36:53

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()
}
mesut

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!