【问题标题】:How can I create a segue form UIViewController to UICollectionViewController ? - Programmatically如何创建从 UIViewController 到 UICollectionViewController 的转场? - 以编程方式
【发布时间】:2021-03-09 01:15:15
【问题描述】:

我可以创建一个应用程序来做一些事情,然后对 UICollectionViewController 进行 segue 吗?

现在得到这个错误: " 由于未捕获的异常 'NSInvalidArgumentException' 导致应用程序终止,原因:'UICollectionView 必须使用非零布局参数初始化'"

当然,我可以在 SceneDelegate 中启动它,但我不希望我的 UICollectionViewController 是第一个视图。

使用 ViewController 时的 SceneDelegate

 func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    
    guard let scene = (scene as? UIWindowScene) else { return }
    
    window = UIWindow(windowScene: scene)
    window?.rootViewController = ViewController()
    window?.makeKeyAndVisible() 
}

当我使用 UICollectionViewController 时的 SceneDelegate

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    
    guard let scene = (scene as? UIWindowScene) else { return }
    
    window = UIWindow(windowScene: scene)
    window?.makeKeyAndVisible()

    let layout = UICollectionViewFlowLayout()
    layout.scrollDirection = .horizontal
    let navController = CollecionViewController(collectionViewLayout: layout)
    window?.rootViewController = navController
    
}

这是我的 ViewController,当我按下按钮时我想在其中进行转场

import UIKit

类视图控制器:UIViewController {

var button = UIButton()

var button2 = UIButton()

var button3 : UIButton = {
    let button = UIButton(type: .system)
    button.setTitle("Push to 3 View Controller", for: .normal)
    button.backgroundColor = .white
    button.setTitleColor(.black, for: .normal)
    button.frame = CGRect(x: 100, y: 300, width: 200, height: 50)
    button.addTarget(self, action: #selector(didTap3Button), for: .touchUpInside)
    
    return button
}()

@objc func didTap3Button() {
  let rootVC = CollecionViewController()
    let navVC = UINavigationController(rootViewController: rootVC)
    present(navVC, animated: true)
    
}

【问题讨论】:

  • 好的,非常感谢 - 我实现了这个:'@objc func didTap3Button () { let layout = UICollectionViewFlowLayout () let navVC = CollecionViewController (collectionViewLayout: layout) present (navVC, animated: true) } '
  • @Sweeper 一切正常 - 它可以工作

标签: ios swift uiviewcontroller uicollectionview programmatically


【解决方案1】:

您应该完全按照您在 didTap3Button 的第二个代码 sn-p 中所做的操作,但不要将其设置为 rootViewControllerpresent navController。您的 Collection VC 需要一个布局。

@objc func didTap3Button() {
    let layout = UICollectionViewFlowLayout()
    layout.scrollDirection = .horizontal
    let rootVC = CollecionViewController(collectionViewLayout: layout)
    let navVC = UINavigationController(rootViewController: rootVC)
    present(navVC, animated: true)
}

【讨论】:

  • 我还不能 - “感谢您的反馈!声望低于 15 人的投票会被记录下来,但不要更改公开显示的帖子得分。”
猜你喜欢
  • 1970-01-01
  • 2011-02-10
  • 1970-01-01
  • 2015-07-27
  • 2011-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多