如何创建 UIViewController 到 UICollectionViewController 的转场形式? - 以编程方式

How can I create a segue form UIViewController to UICollectionViewController ? - Programmatically

我可以创建一个应用程序,在其中执行一些操作,然后转至 UICollectionViewController 吗?

现在得到这个错误: “由于未捕获的异常 'NSInvalidArgumentException',正在终止应用程序,原因:'UICollectionView must be initialized with a non-nil layout parameter' “

当然,我可以在 SceneDelegate 中启动它,但我不想让我的 UICollectionViewController 成为第一个视图。

SceneDelegate 当我使用 ViewController

 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() 
}

当我使用 UICollection 时的 SceneDelegateViewController

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 我想在按下按钮时进行 segue 的地方

import UIKit

class ViewController: 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)
    
}

您应该完全按照在 didTap3Button 中的第二个代码片段中所做的操作,但不要将其设置为 rootViewControllerpresentnavController。您的 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)
}