UICollectionView horizontal paging not centring after rotation - ios

I am currently working on a horizontal gallery scroll view. I have decided to use UICollectionView with horizontal paging enabled. It almost works great... expect on rotation the collection view cells are not centred (see screenshot attached), where red is the first cell and yellow is the second one.
It usually works fine on the first rotation but then just messes up :D
This is the code I have for setting up the class:
class GalleryScrollView: UIView {
private var collectionView: UICollectionView!
private var layout: UICollectionViewFlowLayout!
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setupView()
}
override func layoutSubviews() {
layout.invalidateLayout()
}
private func setupView() {
layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
collectionView = UICollectionView(frame: self.frame,
collectionViewLayout: layout)
collectionView.register(UINib(nibName: "PhotoGalleryCell", bundle: nil), forCellWithReuseIdentifier: "photoGalleryCell")
collectionView.isPagingEnabled = true
collectionView.contentInsetAdjustmentBehavior = .never
collectionView.dataSource = self
collectionView.delegate = self
collectionView.autoresizingMask = .flexibleWidth
collectionView.translatesAutoresizingMaskIntoConstraints = false
collectionView.backgroundColor = .green
self.addSubview(collectionView)
NSLayoutConstraint.activate([
collectionView.leadingAnchor.constraint(equalTo: self.leadingAnchor),
collectionView.trailingAnchor.constraint(equalTo: self.trailingAnchor),
collectionView.topAnchor.constraint(equalTo: self.topAnchor),
collectionView.bottomAnchor.constraint(equalTo: self.bottomAnchor)
])
collectionView.reloadData()
}
}
Followed by the collection view setup:
extension GalleryScrollView: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "photoGalleryCell", for: indexPath) as? PhotoGalleryCell else {
return UICollectionViewCell()
}
if indexPath.item == 0 {
cell.backgroundColor = .red
} else {
cell.backgroundColor = .yellow
}
return cell
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
2
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
return self.frame.size
}
I tried playing around with func collectionView(_ collectionView: UICollectionView, targetContentOffsetForProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint { but for some reason the func was never called.
Did anyone else run into this problem? I saw a lot of topics in objective c threads, not much in swift. I am also somewhat struggling to understand why this is happening, so just understanding the problem would be very helpful. Thank you!

You don't seem to have handled rotations. You need to reloadData when a rotation occurs. You'll get the event in UIViewController from there you can call reloadData on the instance of your UICollectionView.
class GalleryViewController: UIViewController {
//...
var galleryScrollView: GalleryScrollView
//...
override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
super.willTransition(to: newCollection, with: coordinator)
galleryScrollView.collectionViewLayout.invalidateLayout()
}
//...
}
Then in GalleryScrollView:
class GalleryScrollView: UIView {
var currentVisibleIndexPath = IndexPath(row: 0, section: 0)
//....
}
extension GalleryScrollView: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
//...
func collectionView(_ collectionView: UICollectionView, targetContentOffsetForProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint {
let attributes = collectionView.layoutAttributesForItem(at: currentVisibleIndexPath)
let newOriginForOldIndex = attributes?.frame.origin
return newOriginForOldIndex ?? proposedContentOffset
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let center = CGPoint(x: scrollView.contentOffset.x + (scrollView.frame.width / 2), y: (scrollView.frame.height / 2))
if let indexPath = self.screenView.indexPathForItem(at: center) {
currentVisibleIndexPath = indexPath
}
}
}

Related

UICollectionview how to avoide top bar by scrolling

When I start my App everything is fine.
As it should stay.
But as soon I start to scroll down a strange Bar at the Top appears.
Strange Bar by Scrolling down
I looked for some frame issue but I can't find one. I have no Idea what causes this behavior. I coded my UICollectionview programmatically.
Here is my Code:
import UIKit
// MARK: Erzeugung & Füllen des Daten STRUCT
struct Profile {
let name: String
let location: String
let imageName: String
let profession: String
}
var profiles: [Profile] = []
private func populateProfiles() {
profiles = [
Profile(name: "Thor", location: "Boston", imageName: "astronomy", profession: "astronomy"),
...
Profile(name: "Elon Musk", location: "San Francisco", imageName: "graduate", profession: "graduate")
]
}
class ViewController: UIViewController {
private let collectionView: UICollectionView = {
let viewLayout = UICollectionViewFlowLayout()
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: viewLayout)
// collectionView.backgroundColor = .white
return collectionView
}()
// MARK: Hintergrundbild erzeugen
let imageView : UIImageView = {
let iv = UIImageView()
iv.image = UIImage(named:"Backround-wood")
iv.contentMode = .scaleAspectFill
return iv
}()
private enum LayoutConstant {
static let spacing: CGFloat = 50.0 //Größe der Zwischenräume
static let itemHeight: CGFloat = 500.0 //Zellhöhe
}
override func viewDidLoad() {
super.viewDidLoad()
setupViews()
setupLayouts()
populateProfiles() // finales Befüllen des STRUCT
collectionView.reloadData()
self.collectionView.backgroundView = imageView //Hintergrundbild einfügen
}
// MARK: Rotation - Resize-Cells & Transition
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
coordinator.animate(
alongsideTransition: { _ in self.collectionView.collectionViewLayout.invalidateLayout() },
completion: { _ in }
)
}
private func setupViews() {
view.backgroundColor = .white
view.addSubview(collectionView)
collectionView.dataSource = self
collectionView.delegate = self
collectionView.register(ProfileCell.self, forCellWithReuseIdentifier: ProfileCell.identifier)
collectionView.contentInsetAdjustmentBehavior = .never // Cells starten weiter oben
}
// MARK: Constraints collectionView
private func setupLayouts() {
collectionView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
collectionView.topAnchor.constraint(equalTo: view.topAnchor), //view.safeAreaLayoutGuide.topAnchor),
collectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor), //view.safeAreaLayoutGuide.bottomAnchor),
collectionView.leftAnchor.constraint(equalTo: view.leftAnchor),
collectionView.rightAnchor.constraint(equalTo: view.rightAnchor)
])
}
init() {
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension ViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return profiles.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ProfileCell.identifier, for: indexPath) as! ProfileCell
let profile = profiles[indexPath.row]
cell.setup(with: profile)
cell.contentView.backgroundColor = .red
return cell
}
}
extension ViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = itemWidth(for: view.frame.width, spacing: LayoutConstant.spacing)
return CGSize(width: width, height: LayoutConstant.itemHeight)
}
func itemWidth(for width: CGFloat, spacing: CGFloat) -> CGFloat {
let itemsInRow: CGFloat = 2
let totalSpacing: CGFloat = 2 * spacing + (itemsInRow - 1) * spacing
let finalWidth = (width - totalSpacing) / itemsInRow
return floor(finalWidth)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: LayoutConstant.spacing, left: LayoutConstant.spacing, bottom: LayoutConstant.spacing, right: LayoutConstant.spacing)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return LayoutConstant.spacing
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return LayoutConstant.spacing
}
}
Can somebody please help?
This is probably a navigation bar that is initially invisible in iOS 15, but becomes visible when content is being scrolled underneath.
You can hide the navigation bar by adding this in viewDidLoad or viewDidAppear :
navigationController?.setNavigationBarHidden(true, animated: false)

UICollectionView inside of UICollectionView with dynamic height

I am trying to create a similar layout to the App store. I have got one collection view that is vertical and inside of it each row is another collection view that is horizontal.
I am trying to use dynamic height so the cell can increase its height based on the content inside. However that never works, it only works when i use sizeForItemAt function to explicitly set it. I would like to also be able to control the width
I have looked at many previous questions such as: UICollectionView, full width cells, allow autolayout dynamic height? however no answer worked for me.
I am really confused on what i am doing wrong.
import UIKit
class HomeViewController: UICollectionViewController {
public override func viewDidLoad() {
super.viewDidLoad()
let collectionViewLayout = UICollectionViewFlowLayout()
collectionViewLayout.scrollDirection = .vertical
collectionViewLayout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
collectionView.collectionViewLayout = collectionViewLayout
collectionView.translatesAutoresizingMaskIntoConstraints = false
collectionView?.register(HorizontalCollectionView.self, forCellWithReuseIdentifier: HorizontalCollectionView.reuseIdentifier)
}
public override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 1
}
public override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 4
}
public override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: HorizontalCollectionView.reuseIdentifier, for: indexPath) as? HorizontalCollectionView {
return cell
}
return UICollectionViewCell()
}
}
HorizontalCollectionView.swift
import UIKit
class HorizontalCollectionView: UICollectionViewCell, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
static let reuseIdentifier = "HorizontalCollectionView"
var cellSpancolumns: CGFloat?
override init(frame: CGRect) {
super.init(frame: frame)
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell")
collectionView.delegate = self
collectionView.dataSource = self
addSubview(collectionView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented - Storyboards are not used.")
}
lazy var collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
layout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
let collectionView = UICollectionView(frame: bounds, collectionViewLayout: layout)
collectionView.translatesAutoresizingMaskIntoConstraints = false
collectionView.showsHorizontalScrollIndicator = false
return collectionView
}()
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 3
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
if (indexPath as NSIndexPath).section == 0 {
cell.backgroundColor = UIColor.blue
} else {
cell.backgroundColor = UIColor.red
}
return cell
}
}

My cells in the UICollectionViewController disappear

I have created a TableViewController and made a header on it. I added a UICollectionViewController into the header. When I am tapping on cells, they are disappearing. Did anyone have the same issue?
import UIKit
class HeaderController {
override init(frame: CGRect) {
super.init(frame: frame)
let categoryCollectionController = CategoryCollectionController(collectionViewLayout: UICollectionViewFlowLayout())
let categoryView = categoryCollectionController.view!
categoryView.translatesAutoresizingMaskIntoConstraints = false
addSubview(categoryView)
NSLayoutConstraint.activate([
categoryView.leftAnchor.constraint(equalTo: leftAnchor),
categoryView.rightAnchor.constraint(equalTo: rightAnchor),
categoryView.topAnchor.constraint(equalTo: topAnchor),
categoryView.bottomAnchor.constraint(equalTo: bottomAnchor)
])
}
}
class CategoryCollectionController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
let cellID = "UID"
override func viewDidLoad() {
super.viewDidLoad()
collectionView.backgroundColor = .red
collectionView.register(CellCategory.self, forCellWithReuseIdentifier: cellID)
if let layout = collectionViewLayout as? UICollectionViewFlowLayout {
layout.scrollDirection = .horizontal
}
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 10
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellID, for: indexPath) as! CellCategory
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 100, height: 100)
}
}
You can fix this by keeping a reference to the collection view on the header.
Without keeping a reference to the collection view (and not just it's weak view property you've added as a subview), it will be thrown out once init exits scope.
For example:
class HeaderController: UIView {
let categoryCollectionController = CategoryCollectionController(collectionViewLayout: UICollectionViewFlowLayout())
override init(frame: CGRect) {
super.init(frame: frame)
let categoryView = categoryCollectionController.view!
categoryView.translatesAutoresizingMaskIntoConstraints = false
addSubview(categoryView)
NSLayoutConstraint.activate([
categoryView.leftAnchor.constraint(equalTo: leftAnchor),
categoryView.rightAnchor.constraint(equalTo: rightAnchor),
categoryView.topAnchor.constraint(equalTo: topAnchor),
categoryView.bottomAnchor.constraint(equalTo: bottomAnchor)
])
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}

How to implement content view above UICollectionView

I am trying to get the UICollectionView, and UIView above it, to scroll together. I've done a couple of diagrams (before and after scrolling) to show what I'm trying to achieve.
Before scrolling
After scrolling
Currently, I have only been able to get the UICollectionView to scroll within its own section of the screen. I've also tried wrapping both the UIView and UICollectionView into a UIScrollView, although then the UICollectionView doesn't appear on screen.
What's the best way to implement this layout?
Here is a collection view with a section header that scrolls when the collection view scrolls.. If you need a parallax header (stretchy header effect), then there are tons of tutorials online for that..
import UIKit
class Header : UICollectionReusableView {
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.green
}
#available(iOS, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
private var flowLayout: UICollectionViewFlowLayout!
private var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
self.flowLayout = UICollectionViewFlowLayout()
self.flowLayout.scrollDirection = .vertical;
self.flowLayout.minimumInteritemSpacing = 15;
self.flowLayout.minimumLineSpacing = 15;
self.collectionView = UICollectionView(frame: .zero, collectionViewLayout: self.flowLayout)
self.collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "default")
self.collectionView.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "default")
self.collectionView.register(Header.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "header")
self.collectionView.backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 1.0, alpha: 0.5)
self.collectionView.dataSource = self
self.collectionView.delegate = self
self.collectionView.reloadData()
self.view.addSubview(self.collectionView)
self.collectionView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
self.collectionView.leftAnchor.constraint(equalTo: self.view.leftAnchor),
self.collectionView.rightAnchor.constraint(equalTo: self.view.rightAnchor),
self.collectionView.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor),
self.collectionView.bottomAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.bottomAnchor)
])
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 2
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 5
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "default", for: indexPath)
cell.contentView.backgroundColor = UIColor.white
cell.contentView.layer.borderColor = UIColor.red.cgColor
cell.contentView.layer.borderWidth = 1.0
return cell
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
if indexPath.section == 0 && kind == UICollectionElementKindSectionHeader {
let header = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "header", for: indexPath)
return header
}
return collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "default", for: indexPath)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
if section == 0 {
return CGSize(width: collectionView.bounds.width, height: 200.0)
}
return .zero
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let layout = collectionViewLayout as! UICollectionViewFlowLayout
let insets = self.collectionView(collectionView, layout: layout, insetForSectionAt: indexPath.section)
var width = collectionView.bounds.width - 15.0
width -= insets.left + insets.right
return CGSize(width: floor(width), height: 100.0)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsetsMake(10.0, 10.0, 10.0, 10.0)
}
}

Invalid collectionView height

I have some strange problems with collectionView.
Firstly, I have a UIView subclass with collectionView inside it. It looks like this
class UsersListMenu:UIView, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout{
lazy var collectionView:UICollectionView = {
var layout = UICollectionViewFlowLayout()
layout.scrollDirection = .Horizontal
var collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
collectionView.delegate = self
collectionView.dataSource = self
collectionView.translatesAutoresizingMaskIntoConstraints = false
return collectionView
}()
let cellId = "cellId"
let menuArrayItems = ["Подходящие", "Онлайн", "Новые", "Рядом", "Избранные"]
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(collectionView)
collectionView.leadingAnchor.constraintEqualToAnchor(leadingAnchor).active = true
collectionView.trailingAnchor.constraintEqualToAnchor(trailingAnchor).active = true
collectionView.topAnchor.constraintEqualToAnchor(topAnchor).active = true
collectionView.bottomAnchor.constraintEqualToAnchor(bottomAnchor).active = true
collectionView.registerClass(UsersListMenuCell.self, forCellWithReuseIdentifier: cellId)
collectionView.backgroundColor = .whiteColor()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellId, forIndexPath: indexPath) as! UsersListMenuCell
cell.label.text = menuArrayItems[indexPath.item]
return cell
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 5
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return CGSizeMake(100, 40)
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
return UIEdgeInsetsZero
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
return 0
}
}
As you see cell height is set to 40. Then I create instance of that view in my ViewController
class UsersListViewController: UIViewController {
var menu:UsersListMenu = {
var menu = UsersListMenu()
menu.translatesAutoresizingMaskIntoConstraints = false
return menu
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(menu)
menu.topAnchor.constraintEqualToAnchor(view.topAnchor, constant: 80).active = true
menu.leadingAnchor.constraintEqualToAnchor(view.leadingAnchor).active = true
menu.trailingAnchor.constraintEqualToAnchor(view.trailingAnchor).active = true
menu.heightAnchor.constraintEqualToConstant(40).active = true
}
}
The problem that menu looks blank - cells cannot be seen
unless I set height of menu in view controller to 100
menu.heightAnchor.constraintEqualToConstant(100).active = true
then it look like this
What happens here ?

Resources