【发布时间】:2017-09-06 09:09:20
【问题描述】:
如何从标签栏控制器以模态方式呈现视图,以便视图覆盖实际视图?
我想用相机构建一个视图。就像“WhatsApp”或“Instagram”一样,中间有一个按钮,用户可以单击该按钮并显示相机视图。
此外,当点击关闭按钮时,用户应该移动他之前所在的选项卡。
【问题讨论】:
标签: ios swift popup uitabbarcontroller
如何从标签栏控制器以模态方式呈现视图,以便视图覆盖实际视图?
我想用相机构建一个视图。就像“WhatsApp”或“Instagram”一样,中间有一个按钮,用户可以单击该按钮并显示相机视图。
此外,当点击关闭按钮时,用户应该移动他之前所在的选项卡。
【问题讨论】:
标签: ios swift popup uitabbarcontroller
我必须在我目前正在构建的应用程序中实现类似的东西,这相对简单,您需要实现 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
}
我没有测试上面的代码,因为我的实现略有不同并且有更多的变量。大体原理是一样的。
让我知道你的进展,如有必要,我会更新答案。
【讨论】:
UITabBarController 并在这个类上实现UITabBarDelegate。在viewDidLoad 中,您需要执行self.delegate = self,然后当您尝试在底部选择一个选项卡时将触发上述方法。 YourViewControllerClass 是与故事板上的视图控制器关联的类(左侧的那个)。您需要继承 UIViewController 并将此类应用于该视图控制器。
YourViewControllerClass 中,您只需要将操作绑定到按钮并调用self.dismiss(animated: true, completion: nil)。这只会关闭视图控制器,如果您在委托方法中返回 false,您的 UITabBarController 仍应位于离开时所在的选项卡上。
YourViewControllerClass
假设你符合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)
}
}
【讨论】:
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: {
})
【讨论】: