swift - 快速从另一个 View Controller 呈现 View Controller 的问题

标签 swift presentviewcontroller

我在呈现另一个 View Controller 时遇到问题。我能够实现这一目标的唯一方法是使用这行代码:

UIApplication.shared.keyWindow?.rootViewController?.present(partyMemberPage, animated: false, completion: nil)

这是整个函数:

func partyMemberPage() {
    let layout = UICollectionViewFlowLayout()
    let partyMemberPage = PartyMemberPage(collectionViewLayout: layout)
    UIApplication.shared.keyWindow?.rootViewController?.present(partyMemberPage, animated: false, completion: nil)

    print("from SplitButton")
}

尽管上面的代码有效,我很好奇为什么下面的代码不起作用。我尝试的所有操作都会收到一条错误,提示我需要使用非零布局参数初始化 UICollectionView。

self.present(partyPage, animated: true, completion: nil)

我几乎肯定我有正确的项目来使用 self.present(),但我无法让它在这个 vc 上工作。

PS:我也很好奇什么时候更改 rootViewController (如第一行代码)是个好主意,以及什么时候可以接受仅以模态方式呈现 View Controller 。我的应用程序将处理存储少量数据,那么长期传输该数据的最佳方式是什么。

非常感谢所有帮助。如果需要,我可以提供更多代码。我对 Swift 和一般编程非常陌生,所以如果某些逻辑有缺陷,请原谅我。谢谢!

最佳答案

除非绝对必要,否则不应调用根窗口来呈现 View Controller 。本质上,您可以将 Controller 视为浏览器窗口中的选项卡。像这样返回到窗口就像清除所有选项卡(有点)。

至于为什么 self.present() 不起作用,可能有几个原因。

如果您使用 Storyboard,您需要以不同的方式引用您的 View :P

如果抛出错误,请再次尝试使用 self.present(),请阅读它或将其与您的问题一起发布

completion: nil 是不必要的。

由于我不知道您的具体情况,所以我只能给您一些选择。我将第一个 View 称为 VC1,第二个 View 称为 View VC2

  1. 将 VC1 封装在导航 Controller 中,然后尝试使用 .push()
  2. 将 VC2 封装在导航 Controller 中,如下所示:(我在自己的项目中使用此代码,以便验证它是否有效)
 let loginView = UINavigationController(rootViewController: LoginViewController())
            loginView.modalTransitionStyle = .flipHorizontal
            self.present(loginView, animated: true) 
  • 按照我上面的方式指定模式转换
  • 关于swift - 快速从另一个 View Controller 呈现 View Controller 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55789637/

    相关文章:

    ios - 如何使用表格 View 制作粘性页脚和页眉?

    swift - 如何获取/Users/Shared/的 URL

    ios - PFFile 无法将文件存储到解析服务器

    ios - Swift TextField 不接收数据

    ios - 如何同时呈现两个 View Controller ?

    uiviewcontroller - iOS 8- viewController my_shouldAutopresent在PresentViewController时崩溃

    ios - 在 swift 警报中使用哪个标识符代替 "present"

    ios - presentViewController 不存在

    ios - 如何使用 Swift 3 iOS10 为 MPMediaPickerControllerDelegate 的 View Controller 呈现音乐库?

    ios - 崩溃专门的 String.imageSize(),