【问题标题】:Present a View Controller modally from a tab bar controller从标签栏控制器模态显示视图控制器
【发布时间】:2020-04-08 03:29:45
【问题描述】:

我想用相机构建一个视图。就像 Instagram 一样,中间有一个按钮,用户可以单击该按钮并显示相机视图。 我在AppDelegate 中实现了TabViewController 的代码,但没有任何反应,没有动画或新ViewController 的演示文稿。

这是我的 AppDelegate:

import UIKit


class AppDelegate: UIResponder, UIApplicationDelegate, UITabBarControllerDelegate {
    var window: UIWindow?
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: ViewController) -> Bool {
    if viewController is ViewController {
        let storyboard = UIStoryboard(name: "Main.storyboard", bundle: nil)
        if let controller = storyboard.instantiateViewController(withIdentifier: "cameraVC") as? ViewController {
            controller.modalPresentationStyle = .fullScreen
            tabBarController.present(controller, animated: true, completion: nil)
        }
        return false
    }
    return true
}

这是我的故事板:

有什么想法吗?

【问题讨论】:

  • 尝试从主队列调用此行:tabBarController.present(controller, animated: true, completion: nil)

标签: ios swift uitabbarcontroller


【解决方案1】:

我建议为您的 TabBarController 创建一个自定义类,然后将委托分配给它。

您可以分配并检查视图控制器的restorationIdentifier,或者进行类型检查。我通常使用故事板标识符作为视图控制器的恢复标识符。

class TabBarController: UITabBarController, UITabBarControllerDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        self.delegate = self
    }

    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        if let identifier = viewController.restorationIdentifier, identifier == "cameraVC" {
            let vc = self.storyboard?.instantiateViewController(withIdentifier: "cameraVC") as! CameraViewController
            present(vc, animated: true, completion: nil)
            return false
        }

        return true
    }
}

您可以使用以下示例: https://gist.github.com/emrekyv/3343aa40c24d7e54244dc09ba0cd95df

【讨论】:

  • 这有帮助!谢谢
  • 嘿?,我用要点替换了链接。
  • @emrekyv 要点是 404
  • @emrekyv 我认为您需要从链接末尾删除edit。删除后我可以访问它。另外,谢谢:它确实有很大帮助。
  • 不错,已修复!
【解决方案2】:

我刚试过,对我来说效果很好:

为您的 TabBarController 创建一个自定义类并将其分配给 Storyboard 中的控制器。

之后覆盖 tabBarController 的 didSelect 并在那里编写您的演示代码:

override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {

      if let controller = self.viewControllers?[self.selectedIndex] as? ViewController {

          controller.modalPresentationStyle = .fullScreen
          self.present(controller, animated: true, completion: nil
       }
}

希望对你有帮助!!

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多