从标签栏控制器以模态方式呈现视图
如何从标签栏控制器以模态方式呈现视图,以便视图能够覆盖实际视图?从标签栏控制器以模态方式呈现视图
我想用相机构建一个视图。就像“WhatsApp”或“Instagram”,中间有一个按钮,用户可以点击并显示相机视图。
此外,当点击关闭按钮时,用户应该移动他以前的标签。
This is how my ViewController is connected to the TabBarController
我已经实现在一个应用程序目前我正在建设类似的东西,它是相对直接做,你需要实现UITabBarController
的代理方法,以实现这一目标。
你需要实现的委托方法是: tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool
从这个方法返回false将选择您的制表位的制表控制器,那么只需要实现自己的逻辑来呈现UIViewController
编程。
下面是一个例子:
func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
// If your view controller is emedded in a UINavigationController you will need to check if it's a UINavigationController and check that the root view controller is your desired controller (or subclass the navigation controller)
if viewController is YourViewControllerClass {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
if let controller = storyboard.instantiateViewController(withIdentifier: "storyboardID") as? YourViewControllerClass {
controller.modalPresentationStyle = .fullScreen
self.present(controller, animated: true, completion: nil)
}
return false
}
// Tells the tab bar to select other view controller as normal
return true
}
我没有测试上面的代码,我的实现略有不同,有更多的变数。一般原则是一样的。
让我知道你如何得到,我会在必要时更新答案。
let modalVC = self.storyboard?.instantiateViewController(withIdentifier: "ViewControllerIdentifier")
modalVC.modalTransitionStyle = .crossDissolve
modalVC.modalPresentationStyle = .full or .overfullscreen // please check which of the options work
self.present(modalVC, animated: true, completion: {
})
我应该在哪里放这段代码片段? –
假设你符合UITabBarControllerDelegate,你可以实现:
func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
// here, you should edit "0" to be matched with your selected item
// for instance, if there is 5 items and the desired item is in the middle, the compared value should be "2"
if tabBarController.selectedIndex == 0 {
// simply, you will need to get the desired view controller and persent it:
let desiredStoryboard = UIStoryboard(name: "Main", bundle: nil)
let desiredViewController = desiredStoryboard.instantiateViewController(withIdentifier: "storyboard id")
present(desiredViewController, animated: true, completion: nil)
}
}
我直接在故事板中建立了关系segue,所以标签栏项自动创建。所以我已经有一个视图连接到标签栏控制器,但是,我不想使用它,因为我不想切换到另一个视图。我希望它弹出。我该怎么办? –
你能否详细说明一下? –
去检查我原来的帖子。我的问题是,不是以模态方式呈现视图,而是由于TabBarController切换到视图。它是这样做的,因为我像这样实现它,但现在我要求如何不切换视图,而是以模态方式显示。这样它就会弹出我的实际观点。 –
我用你的代码,它仍然不工作,它如何工作。于是为我的TabBarController创建了一个新类并粘贴了你的代码。那是你的意思吗?我应该写哪个类而不是YourViewControllerClass?也许你可以看看我的照片,我在原始帖子中链接了这张照片。 –
嘿,你需要继承你的'UITabBarController'并在这个类上实现'UITabBarDelegate'。在'viewDidLoad'中,你需要执行'self.delegate = self',那么当你尝试在底部选择一个标签时,上面的方法会被触发。 'YourViewControllerClass'是与故事板上的视图控制器(左侧的视图控制器)关联的类。你将需要子类'UIViewController'并将这个类应用到该视图控制器。 – WsCandy
Yeey!有用。非常感谢你的帮助。我忘了self.delegate = self。现在,如果我想用一个按钮关闭它,我怎么才能设法返回到ViewController是否正确? –