【问题标题】:"Attempt to present VC on VC whose view is not in the window hierarchy!" when button pressed from tableview“尝试在视图不在窗口层次结构中的 VC 上呈现 VC!”当从 tableview 按下按钮时
【发布时间】:2019-05-31 17:20:38
【问题描述】:

尝试构建我的第一个应用程序。使用 TableView 呈现 4 个不同的部分。每个部分都有自己的单元格类型,在 .xib 文件中定义。在 TableView 的最后一部分,一个单元格显示有两个按钮,加号和减号。

例如,当按下加号按钮时,它会调用与单元格相关的类中的以下代码:

// link to the viewcontroller with the tableview in it
let mainViewController = ViewController()

// func called when plusbutton is tapped
@IBAction func plusButtonTapped(_ sender: UIButton) {
    // viewcontroller that should popup when the button is tapped
    let popup = PopupViewController()
    let sbPopup = SBCardPopupViewController(contentViewController: popup)
    // call to show()
    sbPopup.show(onViewController: mainViewController)
}


// show() function that is called
public func show(onViewController viewController: UIViewController) {
        self.modalPresentationStyle = .overCurrentContext
        viewController.present(self, animated: false, completion: nil)
 }

当我在模拟器中点击按钮时,它应该会显示 PopupViewController,但会显示以下警告:

 Warning: Attempt to present "balance1.SBCardPopupViewController:     0x7fdf8752cb20> on <balance1.ViewController: 0x7fdf8743cac0> whose view is not in the window hierarchy!

我尝试研究该警告并发现了一些与之相关的其他主题。没有一个解决方案对我有用。也许这与我从 .xib 文件中定义的单元格调用 plusButtonTapped() 的事实有关?

我在 youtube 上关注了这个教程:https://www.youtube.com/watch?v=9yUIOjykPDU 一切都很顺利,直到 10:36,show() 在调用函数的按钮所在的同一 VC 上被调用。在我的例子中,调用 show() 函数的 plusButton 位于一个单独的 .xib 文件中定义的单元格上,因此不在(主)VC 上(如教程中所示)。这与我面临的问题有什么关系吗?

【问题讨论】:

    标签: ios swift uitableview uiviewcontroller xib


    【解决方案1】:

    错误消息看起来是正确的。看看你的代码,“悬空”的 mainViewController 还没有被添加到窗口中。

    // link to the viewcontroller with the tableview in it
    let mainViewController = ViewController()
    

    这一行上面的这个注释似乎表明它是一个到父视图控制器的链接,但它实际上是一个新实例化的视图控制器。您需要通过层次结构向下传递实际的父级以实现您正在尝试的目标。

    如果你给每个单元格一个“presentationDelegate”,你可以更轻松地处理所有卡片的展示。

    【讨论】:

    • 是的,我认为你是对的。关于如何将实际父 VC 向下传递层次结构的任何建议?我的猜测是: func plusButtonTapped (){ .... let storyboard = UIStoryboard(name: "MainViewController", bundle: nil) let controller = storyboard.instantiateViewController(withIdentifier: "ViewController") // 调用 show() sbPopup .show(onViewController: controller) }(带有tableView的VC的故事板ID是:“MainViewController”)
    • 上面的评论很难阅读。这里有格式化代码:func plusButtonTapped (){ .... let storyboard = UIStoryboard(name: "MainViewController", bundle: nil) let controller = storyboard.instantiateViewController(withIdentifier: "ViewController") // call to show() sbPopup.show(onViewController: controller) }
    • 当您在developer.apple.com/documentation/uikit/uitableviewdatasource/… 中创建单元格时,您可以传入接收器以在单元格本身中执行操作。
    • 通过删除 .xib 文件并将单元格直接复制到 TVC 中来解决问题。这意味着我可以调用 show(onViewController: self)。解决了这个问题。感谢您的帮助!
    猜你喜欢
    • 2013-05-04
    • 2017-07-18
    • 2015-03-30
    • 1970-01-01
    • 1970-01-01
    • 2014-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多