Swift 如何从嵌入式视图访问选项卡栏?
我的应用程序中有一个选项卡栏控制器,它有4个选项卡。其中一个应该根据API的响应显示两个场景中的一个:如果没有数据,则显示空视图;如果有数据,则显示分段控件。 以下是带有设置的故事板: 在空视图和包含数据的视图上,我都有一个按钮,该按钮应该“单击”选项卡栏上的一个按钮(切换到另一个选项卡) 现在我正在做的就是: 显示包含数据的视图:Swift 如何从嵌入式视图访问选项卡栏?,swift,uitabbarcontroller,navigationcontroller,Swift,Uitabbarcontroller,Navigationcontroller,我的应用程序中有一个选项卡栏控制器,它有4个选项卡。其中一个应该根据API的响应显示两个场景中的一个:如果没有数据,则显示空视图;如果有数据,则显示分段控件。 以下是带有设置的故事板: 在空视图和包含数据的视图上,我都有一个按钮,该按钮应该“单击”选项卡栏上的一个按钮(切换到另一个选项卡) 现在我正在做的就是: 显示包含数据的视图: class EmptyTasksVC: ViewController { override func viewDidLoad() { s
class EmptyTasksVC: ViewController {
override func viewDidLoad() {
super.viewDidLoad()
if(there_is_data){
let storyboard = UIStoryboard(name: "TaskTodoList", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "TaskListSegmentedControl")
let childNavigation = UINavigationController(rootViewController: vc)
childNavigation.willMove(toParent: self)
addChild(childNavigation)
childNavigation.view.frame = view.frame
view.addSubview(childNavigation.view)
childNavigation.didMove(toParent: self)
}
}
}
@objc func newTaskAction(sender: UIButton!) {
let viewController = self.findViewController()
let tabBar = viewController?.parent?.parent?.parent?.parent?.parent as! UITabBarController
tabBar.selectedIndex = 2
}
...
extension UIView {
func findViewController() -> UIViewController? {
if let nextResponder = self.next as? UIViewController {
return nextResponder
} else if let nextResponder = self.next as? UIView {
return nextResponder.findViewController()
} else {
return nil
}
}
}
查找按钮上的选项卡栏,从包含数据的视图中单击:
class EmptyTasksVC: ViewController {
override func viewDidLoad() {
super.viewDidLoad()
if(there_is_data){
let storyboard = UIStoryboard(name: "TaskTodoList", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "TaskListSegmentedControl")
let childNavigation = UINavigationController(rootViewController: vc)
childNavigation.willMove(toParent: self)
addChild(childNavigation)
childNavigation.view.frame = view.frame
view.addSubview(childNavigation.view)
childNavigation.didMove(toParent: self)
}
}
}
@objc func newTaskAction(sender: UIButton!) {
let viewController = self.findViewController()
let tabBar = viewController?.parent?.parent?.parent?.parent?.parent as! UITabBarController
tabBar.selectedIndex = 2
}
...
extension UIView {
func findViewController() -> UIViewController? {
if let nextResponder = self.next as? UIViewController {
return nextResponder
} else if let nextResponder = self.next as? UIView {
return nextResponder.findViewController()
} else {
return nil
}
}
}
如果我想从空视图进入按钮,我必须从链中删除2个“父”
一定有更好的办法。。。
我的架构错了吗?如果我不知道有多少视图正在进行中,如何从嵌入式视图访问选项卡栏?A
ViewController
已经有一个属性tabBarController
,其描述如下
//如果视图控制器的祖先为选项卡栏控制器,
归还它。否则返回零
因此,您可以直接访问viewController嵌入的选项卡栏
控制器
self.tabBarController?.selectedIndex = 2
我认为这对嵌入容器视图的控制器不起作用。我现在觉得自己像个白痴。出于某种原因,我认为如果我不在tabBarViewController中,就不可能访问它。谢谢你,好心的先生@MartaPanuszewska没关系,这是过程的一部分。继续工作:)