Here is a screenshot of what I want to achieve:
I need this type of collection view layout for card cells (with leading and trailing edging displays).
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var colList : UICollectionView!
var arrData = [1,2,3]
override func viewDidLoad() {
super.viewDidLoad()
self.colList.delegate = self
self.colList.dataSource = self
let nib = UINib(nibName: "CardCell", bundle: nil)
self.colList.register(nib, forCellWithReuseIdentifier: "CardCell")
}
}
extension ViewController : UICollectionViewDataSource, UICollectionViewDelegate , UICollectionViewDelegateFlowLayout{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return arrData.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CardCell", for: indexPath) as? CardCell
cell?.setUpData(data: "(indexPath.row)")
return cell ?? UICollectionViewCell()
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: (collectionView.frame.width) - 40 , height: collectionView.frame.height)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
let cellWidth : CGFloat = (collectionView.frame.width) - 40
let numberOfCells = floor(collectionView.frame.size.width / cellWidth)
let edgeInsets = (collectionView.frame.size.width - (numberOfCells * cellWidth)) / (numberOfCells + 1)
return UIEdgeInsets(top: 0, left: edgeInsets, bottom: 0, right: edgeInsets)
}
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 40
}
}
However, when I run the code my cell looks like this:
I can’t see the leading and trailing edges for the previous and next cards.
2
Answers
Just edit your minimunInterspacing function and give some value.
And with this make sure that you have called the delegate method to your class like UICollectionViewDataSource. You also have to check that you added
collectionViewOutletName.delegate = self
anddataSource
inviewDidLoad
.The issue is here in
sizeForItem
function. you are returning very extra width for cell which makescollectionView
not to show the other cells.Your cell needs a little more less width then you provided.