如何创建按下选项卡栏上的按钮时出现的弹出窗口?我想要类似的东西:https://www.youtube.com/watch?v=zDWSaItF2ko .
我尝试了很多解决方案,但没有一个有效。
例如,我已经用我的主视图 Controller 尝试过此操作:
但这仍然不起作用。我将如何着手创建这个。我知道我需要在当前上下文中以模态方式呈现 View Controller ,但是我如何从选项卡栏 Controller 中做到这一点。
func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
if viewController is PopupViewController {
if let popupView = tabBarController.storyboard?.instantiateInitialViewController() {
popupView.modalPresentationStyle = .fullScreen
tabBarController.present(popupView, animated: true, completion: nil)
return false
}
}
return true
}
以下是一些可能有帮助的图片:
主要 Storyboard:
弹出 Storyboard:
查看 Controller 代码:
最佳答案
您是否尝试过在 Xcode 中使用断点进行调试?据我所知,您要做的第一件事是检查应该选择的 View Controller 是否属于 PopupViewController
类。您确定 View Controller 已正确实例化吗?
顺便说一句,我会推荐另一种从 Storyboard实例化 View Controller 的方法:
tabBarController.storyboard?.instantiateInitialViewController()
第一件事是转到 Storyboard文件本身,并在 View Controller 中尝试实例化,将Storyboard ID
更改为例如 Storyboard的类(PopupViewController
在你的情况下)。
接下来,您将尝试使用 init(name: String, bundlestoryboardBundleOrNil: Bundle?)
初始化器实例化 Storyboard本身:
let storyboard = UIStoryboard(name: "Popup", bundle: nil)
现在使用 storyboard
变量实例化 View Controller ,如下所示:
let popupViewController = storyboard.instantiateViewController(withIdentifier: "PopupViewController") as! PopupViewController
最后,您可以给它一些额外的配置并将其呈现在标签栏 Controller 上:
popupViewController.modalPresentationStyle = .fullScreen
tabBarController.present(popupViewController, animated: true)
编辑
此外,为了使其更加Swifty,我建议使用 guard
语句来提前退出。最后该方法可能如下所示:
func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
guard viewController is PopupViewController else { return true }
let storyboard = UIStoryboard(name: "Popup", bundle: nil)
let popupViewController = storyboard.instantiateViewController(withIdentifier: "PopupViewController") as! PopupViewController
popupViewController.modalPresentationStyle = .fullScreen
tabBarController.present(popupViewController, animated: true, completion: nil)
return false
}
关于ios - 如何从选项卡栏 Controller 弹出或模态呈现 View Controller ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50471430/