This isn\'t my desired effect. This only happens when the collection view is set to horizontal flow layout. I\'ve seen a few other posts regarding this very same issue but none
Okay so I've found a solution to this problem. I came across this in a couple of other threads on stackoverflow regarding a similar incident, in one case the Answer had no votes attributed to it and a comment left to the answer said it didn't work..
Though after all this I'm still not crystal clear on why the other implementation causes the collection view to shift up. Though there is some correlation between the window, root view controller and it's subviews along with the keyboard. Why this happens I don't know.
Now on to the code and fix..
The main different between the method in the question above and here is the way the collection view is initialised. I'll only post what I changed because the rest is just the same.
AppDelegate.swift
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
let rvc = ViewController()
window? = UIWindow()
window?.makeKeyAndVisible()
window?.rootViewController = rvc
return true
}
}
The striking difference here is the root view controller is no longer initialised with the Collection View Controller. We use a standard View Controller.
ViewController.swift
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
lazy var collView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
let view = UICollectionView(frame: .zero, collectionViewLayout: layout)
view.dataSource = self
view.delegate = self
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.darkGray
collView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cellId")
collView.register(HomeCell.self, forCellWithReuseIdentifier: "homeCellId")
self.view.addSubview(collView)
collView.backgroundColor = UIColor.blue
collView.translatesAutoresizingMaskIntoConstraints = false
collView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
collView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true
collView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true
collView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
collView.heightAnchor.constraint(equalTo: self.view.heightAnchor, multiplier: 1)
// Do any additional setup after loading the view, typically from a nib.
}
}
We initialise the View Controller with a collectionview as a subview and apply the same code we would normally to the cells