我正在使用 Xcode 8.2 , Swift 3 , iOS 10 。我意识到标题可能很难理解,所以让我解释一下我想要做什么。
我有一个TabViewController
有三个孩子ViewControllers
,每个孩子都有自己的NavigationController
以及之后的其他内容。一个这样的选项卡如下所示(表1)。这是一个TableViewController
,我在其中显示了包含信息的自定义TableView
单元格。
在另一个标签页(例如标签2)上,我点击按钮时将单元格添加到标签1中。我已经让它工作得很好。现在,我想要的行为是当用户点击同一个按钮时(在标签2上),我想添加一个单元格(如前所述),但也要添加该单元格的详细信息视图并跳转到该详细信息视图(而不是必须切换到选项卡1并单击相应的单元格)。在这个详细信息视图中,我希望有一个后退按钮,它将返回到选项卡1,这是访问所有详细信息视图的位置。
我一直在努力找出实现这种行为的正确方法,因此我们将非常感谢任何帮助。谢谢!
修改
我根据Winter的回复做了一些修改。但是,我仍然无法连接"带有表视图单元格的新创建的UIViewController
。
我做了以下事情:
在标签2中:
// this code is located in a function where I call to create a new custom cell in Tab 1.
//Switch to first tab
tabBarController?.selectedIndex = 0
//Show the detail view
if let navigationController = tabBarController?.viewControllers?[0] as? UINavigationController {
let detailViewController = UIViewController()
detailViewController.view.backgroundColor = UIColor.red
navigationController.pushViewController(detailViewController, animated: true)
let tempNavVC = self.tabBarController?.viewControllers?[0] as! UINavigationController
let resultsTab = tempNavVC.viewControllers[0] as! Tab1VC
resultsTab.detailVCArray.append(detailViewController)
}
在标签1中:
// this is an array that holds the newly created view controllers passed in from Tab 2
// when the user clicks on a cell, look up which cell it clicked on and display the view controller for that cell
var detailVCArray = [UIViewController]()
// called when a cell is clicked
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let newChildVC = detailVCArray[indexPath.row]
self.addChildViewController(newChildVC)
self.present(newChildVC, animated: true, completion: nil)
}
当我运行它时,选项卡2中的代码成功执行,我看到一个带有红色背景的新视图控制器。但是,如果单击“表视图”单元格,则会出错:
' NSInvalidArgumentException',原因:'应用程序试图呈现 模块化一个活动控制器
而不是转到相同的红色View Controller。
我意识到这可能是一种非常愚蠢的方式,但我无法想到其他任何事情。
在一天结束时,我希望我的Tab 2在选项卡1中创建一个表视图单元格,其中包含一些带有详细信息的视图控制器和"转换"我对那些细节。
答案 0 :(得分:2)
代码是这样的:
//Click function in viewController of Tab 2
func click(_ sender: Any) {
//Adding cells into Tab 1
//Switch to Tab 1
tabBarController?.selectedIndex = 1
//Show the detail view
if let navigationController = tabBarController?.viewControllers?[1] as? UINavigationController {
let detailViewController = UIViewController()
detailViewController.view.backgroundColor = UIColor.white
navigationController.pushViewController(detailViewController, animated: true)
}
}
//Code in viewController of Tab 1
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//For example: need to show detail view when row is 1
if indexPath.row == 1 {
//Show the detail view
let detailViewController = UIViewController()
detailViewController.view.backgroundColor = UIColor.white
navigationController?.pushViewController(detailViewController, animated: true)
}
}