【问题标题】:Swift tried to present modally an active controller [Current view controller] even though the presented controller is another oneSwift 试图以模态方式呈现一个活动控制器 [当前视图控制器],即使呈现的控制器是另一个控制器
【发布时间】:2018-01-19 16:32:37
【问题描述】:

我已经阅读了一些答案,例如关闭当前的 ViewController,但我的情况有所不同,因为我正在展示另一个 ViewController。

虽然我无法访问它的属性,但这段代码向视图控制器展示了它的导航控制器:

@IBAction func didTouchAddFriend(_ sender: UIButton) {
DispatchQueue.main.async {

    let storyBoard = UIStoryboard(name: "CustomContact", bundle: nil)
        let customContactVC = storyBoard.instantiateViewController(withIdentifier: "CustomContact")

}
}

虽然这个不起作用

@IBAction func didTouchAddFriend(_ sender: UIButton) {
    DispatchQueue.main.async {

        let navigation = UIStoryboard.init(name: "CustomContact", bundle: nil).instantiateInitialViewController() as! UINavigationController
        let pickerUserVC = navigation.viewControllers.first as! CustomContactsViewController
        self.present(pickerUserVC, animated: true, completion: nil)

    }
}

我有另一个名为 CustomContact.storyboard 的故事板,其中包含一个 CustomContactsViewController

当我点击 didTouchAddFriend 时,它只显示这个错误:

'NSInvalidArgumentException', reason: 'Application tried to present modally an active controller <Main.MainViewController: 0x7ff29f06ac00>.'

当我打印 pickerUserVC 的值时,我无法理解错误 cos,它显示了正确的视图控制器:

<Main.CustomContactsViewController: 0x7fd1b7922400>

MainViewController 是当前实现 didTouchAddFriend 函数的视图控制器

【问题讨论】:

    标签: ios swift


    【解决方案1】:

    您应该展示 导航控制器(它承载 CustomContactsViewController 作为它的根视图控制器)。

    此外,您可以跳过 Dispatch 调用,因为我们在一个已经在主线程中运行的 @IBAction 中:

    @IBAction func didTouchAddFriend(_ sender: UIButton) {
        let navigation = UIStoryboard.init(name: "CustomContact", bundle: nil).instantiateInitialViewController() as! UINavigationController
        let pickerUserVC = navigation.viewControllers.first as! CustomContactsViewController
        self.present(navigation, animated: true, completion: nil)
    }
    

    【讨论】:

    • 另外,要关闭 CustomContactsViewController,您需要在显示它的 viewController 上调用 dismiss,navigationController?.presentingViewController?.dismiss(animated: true, completion: nil)
    • 我在 iOS 方面拥有近 7 年的经验,我的工作头衔是“iOS 技术主管”。但是我还是错过了这个! LMAO。我可能应该重新考虑我的职业生涯。或者我只是想用多云的头脑编写代码,并努力在凌晨 2:30 保持清醒。
    猜你喜欢
    • 1970-01-01
    • 2017-02-03
    • 2016-11-20
    • 2015-06-17
    • 1970-01-01
    • 1970-01-01
    • 2014-12-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多