Swift - Create UICollectionViewController without Storyboard


After we create a new project, first thing we need to do is to delete Main.storyboard.




Next Step, go to project general setting -> Deployment Info, delete "Main" on Main Interface

Good, and then we go to ViewController.swift, change Subclass to UICollectionViewController, also change collectionview's background to red color to specify that we are using UICollectionViewController.

import UIKit

class ViewController: UICollectionViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        collectionView.backgroundColor = UIColor.red
    }


}

Then, go to AppDelegate.swift, and now we have to manually build what storyboard do for us. In

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        return true
}

block, add some code like this: 

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        
        window = UIWindow(frame: UIScreen.main.bounds)
        window?.makeKeyAndVisible()
        
        let layout = UICollectionViewFlowLayout()
        let viewController = ViewController(collectionViewLayout: layout)
        window?.rootViewController = UINavigationController(rootViewController: viewController)
        
        return true
}

Now we hit Build and Run Button on top-left of Xcode, see what simulator show for us.



If it appears a red screen with a navigationBar on top of it like the image above, then there you go! You're done and you can configure some property for your collectionview.

留言

這個網誌中的熱門文章

Windows 10 64bits安裝Spyder (Anaconda)

在Spyder IDE 使用Python + OpenCV

Raspberry Pi - 利用AnyDesk遠端到樹莓派,並保持螢幕解析度不縮放