Tell me if this can help you.
I don't use Storyboard.
AppDelegate.swift
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
window = UIWindow(frame: UIScreen.main.bounds)
window?.makeKeyAndVisible()
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
let nineCellsController = NineCellsController(collectionViewLayout: layout)
window?.rootViewController = nineCellsController
return true
}
NineCellsController.swift
import UIKit
class NineCellsController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
let cellIdentifier = "cellIdentifier"
let numberOfCells = 9
override func viewDidLoad() {
super.viewDidLoad()
collectionView?.backgroundColor = .white
setupCollectionView()
}
func setupCollectionView() {
collectionView?.register(UICollectionViewCell.self, forCellWithReuseIdentifier: cellIdentifier)
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return numberOfCells
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath)
cell.backgroundColor = randomColor()
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: view.frame.size.width, height: view.frame.size.height)
}
fileprivate func randomColor() -> UIColor {
let red = CGFloat(drand48())
let green = CGFloat(drand48())
let blue = CGFloat(drand48())
return UIColor(red: red, green: green, blue: blue, alpha: 1)
}
}