如何在单击 tabBar 项 Swift 上刷新 tableView? [英] How to refresh a tableView on click tabBar item Swift?

查看:20
本文介绍了如何在单击 tabBar 项 Swift 上刷新 tableView?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 tableView 到选项卡栏上的 viewController 中.当我点击 tabBar 项目时,tableView 没有刷新.但我有 viewWillAppear 功能:

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

为什么不重新加载?

谢谢!

推荐答案

您无需在此涉及标签栏控制器.这样做会矫枉过正.您将创建令人困惑的代码,稍后有人会想要撕掉这些代码.在 viewWillAppear(_:) 中更新表格视图几乎总是最好的方法.

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.

如果一切设置正确,您的视图控制器的 viewWillAppear(_:) 方法将在每次用户选择该选项卡并且您的视图变为可见时被调用.因此,如果它没有被调用,则说明标签栏及其视图控制器的设计存在问题.

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.

创建一个新项目并选择选项卡式应用程序模板.打开 SecondViewController 文件并添加一个 viewWillAppear(_:) 方法.在那里添加一个断点.每次切换到第二个标签时,您都会看到它被调用.

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.

其他一些想法...

您会在 viewWillAppear(_:) 文档中注意到它说您必须始终调用 super.你不.你应该.但这与您的问题无关.

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.

此外,无需切换到主队列.viewWillAppear(_:) 将始终在主队列上调用.

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

这篇关于如何在单击 tabBar 项 Swift 上刷新 tableView?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆