Issue while collection view cell scroll to center in swift - ios

I have a collection view in my VC, I scroll collection view horizontally, I want to center each cell on scroll horizontally, I have tried a code but when it scrolls it shows next cell more left then the second one .This is my code,
fileprivate let sectionInsets = UIEdgeInsets(top: 0, left: 15, bottom: 0, right: 15)
gridView.delegate = self
gridView.dataSource = self
gridView.register(ItemCollectionViewCell.self, forCellWithReuseIdentifier: "ItemCollectionViewCell")
gridView.register(UINib(nibName: "ItemCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "ItemCollectionViewCell")
gridView.showsHorizontalScrollIndicator = true
gridView.bounces = true
gridView.showsHorizontalScrollIndicator = false
gridView.showsVerticalScrollIndicator = false
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
return auctions?.properties?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
let cell:ItemCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "ItemCollectionViewCell", for: indexPath) as! ItemCollectionViewCell;
cell.propertyData = (auctions?.properties![indexPath.row])!
if auctions?.status == AuctionStatus.Live.rawValue {
cell.noOfBidsPlaced.isHidden = false
}
else {
cell.noOfBidsPlaced.isHidden = true
}
cell.populateCell()
return cell
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
let size = CGSize(width: 335 , height: 337)
return size
}
//3
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
insetForSectionAt section: Int) -> UIEdgeInsets {
return sectionInsets
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat
{
return sectionInsets.left
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return sectionInsets.left
}
How I can scroll each cell to center perfectly?
Here is how it shows my collection on start,
Thats what it shows on scroll, it get cut from left side

Don't use static height and width.
call this function.Maybe its helpful for you:-
// func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
// return CGSize(width: yourCollectionView.frame.size.width, height: yourCollectionView.frame.size.height )
// }

Related

Bottom Collection view spacing issues, I want to remove the blue spacing

I am getting the space between the cells (marked with blue color):
extension ProfileVC: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if collectionView == self.humanCollectionView {
let screenWidth = humanCollectionView.bounds.width
return CGSize(width: screenWidth/3-0, height: screenWidth/3-0)
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout:
UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout:
UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
}
}
Why are you declaring the delegate functions inside collectionView(_ collectionView: UICollectionView, layout: UICollectionViewLayout, sizeForItemAt: IndexPath) delegate method?
Try to do like this:
import UIKit
class ProfileVC: UICollectionViewController {
override func viewDidLoad() {
super.viewDidLoad()
//remember to set the delegates
self.collectionView.delegate = self
self.collectionView.dataSource = self
//this is optional just to test that it is working
collectionView.backgroundColor = .red
// Do any additional setup after loading the view.
}
}
extension ProfileVC: UICollectionViewDelegateFlowLayout {
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
//this is just a test number, here you should return the number of your items
return 20
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
//you should set reuseIndetifier in storyboard or in code if you create your collectionView programmatically
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "reuseIdentifier", for: indexPath)
//again this is just a placeholder color to see that it's working
cell.backgroundColor = .green
return cell
}
func collectionView(_ collectionView: UICollectionView, layout: UICollectionViewLayout, sizeForItemAt: IndexPath) -> CGSize {
let screenWidth = collectionView.bounds.width
//be sure to use floor or to use a number of items that perfectly fits the width of collectionView
return CGSize(width: floor(screenWidth/3), height: floor(screenWidth/3))
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout:
UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout:
UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
}
}
I want to add that if the width of your collectionView is not perfectly divisible by 3, you will always have some gap between the cells. You should do the math by yourself for each device width and choose a proper number of cells for the width. For example for a screen with aspect ratio like iPhone X, I would use 3 cells when in portrait and 4 cells when in landscape.
You can do like this:
func collectionView(_ collectionView: UICollectionView, layout: UICollectionViewLayout, sizeForItemAt: IndexPath) -> CGSize {
let screenWidth = collectionView.bounds.width
let screenHeight = collectionView.bounds.height
let numberOfCells : CGFloat = screenWidth > screenHeight ? 4 : 3
return CGSize(width: floor(screenWidth/numberOfCells), height: floor(screenWidth/numberOfCells))
}

Implementing UICollectionView horizontally | Swift

I am implementing a collection view horizontally, and I want to achieve UI just like in app store.
I want to achieve the spacing that look, i.e UICollectionview cell is in the middle, and showing other cells on the sides. What happening to my code is that I am not able to scroll it to the centre.
Below is the code I am using to achieve what I did so far.
lazy var cardCollectionView : UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
collectionView.translatesAutoresizingMaskIntoConstraints = false
collectionView.delegate = self
collectionView.dataSource = self
collectionView.backgroundColor = .blue
collectionView.isPagingEnabled = true
collectionView.showsHorizontalScrollIndicator = false
return collectionView
}()
Constraints
cardCollectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
cardCollectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
cardCollectionView.topAnchor.constraint(equalTo: label.bottomAnchor, constant: 42)
cardCollectionView.heightAnchor.constraint(equalToConstant: 250),
CollectionViewDelegate Methods
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 4
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: collectionViewCellId, for: indexPath) as! CardCell
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 364, height: 240)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 10
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top:0 , left: 25, bottom:0 , right:0)
}

How to properly add spacing between collection view cells?

I'm currently trying to set spacing between my collection view cells. The issue is every time I scroll horizontally the cell does not reset back to where is should be. I'm using this library for the collection view cell animation: https://github.com/KelvinJin/AnimatedCollectionViewLayout.
Please Look at image bellow!
Here is my code:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// Turn on the paging mode for auto snaping support.
collectionView?.isPagingEnabled = true
if let layout = collectionView?.collectionViewLayout as? AnimatedCollectionViewLayout {
layout.scrollDirection = direction
layout.animator = animator?.0
}
dismissGesture.direction = direction == .horizontal ? .down : .left
}
extension ImageCollectionViewController: UICollectionViewDelegateFlowLayout {
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return Int(Int16.max)
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let c = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath)
if let cell = c as? SimpleCollectionViewCell {
let i = indexPath.row % vcs.count
let v = vcs[i]
cell.bind(color: v.0, imageName: v.1)
cell.clipsToBounds = animator?.1 ?? true
}
return c
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
guard let animator = animator else { return view.bounds.size }
return CGSize(width: view.bounds.width / CGFloat(animator.2), height: view.bounds.height / CGFloat(animator.3))
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return .zero
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 10
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
}
Also here are images showing what happens:

UICollectionView cell overlapping with Header

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let collectionViewWidth = collectionView.bounds.width
let keys = Array(indoordataDictionary.keys)
let keyString:String = keys[indexPath.section]
let objFacilityUserList:FacilityUserList = indoordataDictionary[keyString]! as! FacilityUserList
if objFacilityUserList.facilityUserList.count == 1 {
return CGSize(width: collectionViewWidth, height: 30)
}
return CGSize(width: collectionViewWidth/2, height: 70)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 5
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
if indoorSegment.selectedSegmentIndex == 1 {
return CGSize(width:collectionView.frame.size.width, height:0.0)
}
else {
return CGSize(width:collectionView.frame.size.width, height:40.0)
}
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let headerView: PlaceCollectionReusableView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: TagIDConstant.nibs.kPlaceCollectionReusableViewID, for: indexPath) as! PlaceCollectionReusableView
let keys = Array(indoordataDictionary.keys)
let keyString:String = keys[indexPath.section]
headerView.placeNameLabel.text = keyString
return headerView
}
If you are using the Custom Layout for the CollectionView then the following link is the best class for that, which will solve this Section Header overlapping problem.
https://gist.github.com/olxios/9e0ae85d49529b0d8b8a6fe6e7a00fab
Hope it helps to those who are using the Custom Layout for the CollectionView.

How to set position of cell of collectionview swift?

i am using collectionview to show image in full screen and allowing scrolling between different images. but when orientation will change it's not showing properly..And this is my code
override func willRotate(to toInterfaceOrientation: UIInterfaceOrientation, duration: TimeInterval) {
// collectionView.reloadData()
collectionView.collectionViewLayout.invalidateLayout()
if visibleCell != nil {
collectionView.selectItem(at: visibleCell as IndexPath?, animated: true, scrollPosition: .centeredHorizontally)
}
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return images.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImageCell", for: indexPath) as! ImageCollectionViewCell
print(cell.frame)
cell.SectionImage.image = images[indexPath.row].image
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: self.view.frame.width, height: self.view.frame.height)
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
Use UICollectionView sizeForItemAtIndexPath method to define height and width of cell.
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let leftAndRightPaddings: CGFloat = 15.0
let numberOfItemsPerRow: CGFloat = CGFloat(NUMBER_OF_ITEMS_PER_ROW)
let bounds = UIScreen.mainScreen().bounds
let width = (bounds.size.width - leftAndRightPaddings * (numberOfItemsPerRow+1)) / numberOfItemsPerRow
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize = CGSizeMake(width, width)
return layout.itemSize
}
Try it. And you will get your expected result.
First of all set the minimum spacing for cell and lines to 0.
After that return the size of cell equal to UICollectionView by using the delegate method
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize{
return CGSizeMake(collectionView.frame.size.width, collectionView.frame.size.height)
}
override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {
dispatch_async(dispatch_get_main_queue()) {
self.collectionView.reloadData()
}
print_debug("change orientation")
}
Its work for me in the same situation.

Resources