简体   繁体   English

在TabBarController中使用相同的ViewController和TableView

[英]Use the same ViewController and TableView in a TabBarController

I have the following problem. 我有以下问题。 I'm using a TabBarController with 5 different tabs for each day from Monday to Friday. 从星期一到星期五,我每天使用带有5个不同选项卡的TabBarController

Each tab needs to have only a TableView that display some information depending the current selected tab (aka day). 每个选项卡只需要一个TableView显示一些信息,这些信息取决于当前选择的选项卡(又名“天”)。

I'm using for every tab the same ViewController . 我为每个选项卡使用相同的ViewController I'm using the following method 我正在使用以下方法

func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController)

to detect the current tab bar index and load the data to display in the table. 检测当前的标签栏索引并加载数据以显示在表中。 In my idea this method also updates the variable currentDay which is used to retrieve the correct data to be displayed. 在我的想法中,此方法还更新了变量currentDay ,该变量用于检索要显示的正确数据。

Below the code I use to get such data. 在我用来获取此类数据的代码下面。

let retrieveOrariofromCoreData = CoreDataController.sharedIstanceCData.load(currentDay)
self.arrayTimes = retrieveOrariofromCoreData
if (self.arrayTimes?.isEmpty)! {
    Utils.setPlaceholderForEmptyTable(self, message: "...")
} else {
    self.tableView.reloadData()
    self.tableView.isHidden = false
}

The problem is that I place this code in the viewDidLoad or viewWillAppear method, which is executed before the tabBarController that changes the variable currentDay . 的问题是,我将此代码在viewDidLoadviewWillAppear的方法,其中在之前执行tabBarController改变所述可变currentDay

Maybe my approach is a bit rudimental. 也许我的方法有点基本。 I'd like to find a more simple and elegant way to do that. 我想找到一种更简单,更优雅的方法。

I don't know when you change your currentDay variable. 我不知道何时更改currentDay变量。 I have just tested it with UITabBarControllerDelegate s tabBar:didSelect: , which is executed before loading the viewController. 我刚刚使用UITabBarControllerDelegatetabBar:didSelect:对其进行了测试,该加载在加载viewController之前执行。

My testing code looks like the following: 我的测试代码如下所示:

var index = 0
override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
    index = (self.tabBar.items?.index(of: item)) ?? 0
}

And then in the viewController in viewDidLoad and viewDidAppear : 然后在viewController中的viewDidLoadviewDidAppear

print("loaded \((self.tabBarController as? TabViewController)?.index ?? 0)")

which always gave me the correct index. 总是给我正确的索引。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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