Reputation: 9
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! SkrapCollectionViewCell
cell.myLabel.text = self.items[indexPath.item]
return cell
}
This is my collection view code where I need to place the code to edit the number of columns. It is 6 now.
Upvotes: -1
Views: 4555
Reputation: 807
if you are using a collection view from the storyboard then maybe this solution can work for you
class AbcViewController: UIViewController {
@IBOutlet var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
coachCollectionView.dataSource = self
coachCollectionView.collectionViewLayout = AbcViewController.createLayout()
}
static func createLayout() -> UICollectionViewCompositionalLayout {
let item = NSCollectionLayoutItem(layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .fractionalHeight(1)))
let group = NSCollectionLayoutGroup.horizontal(layoutSize:
NSCollectionLayoutSize(
widthDimension: .fractionalWidth(1),
heightDimension: .fractionalHeight(2/5)),
subitem: item,
count: 2
)
let section = NSCollectionLayoutSection(group: group)
return UICollectionViewCompositionalLayout(section: section)
}}
Upvotes: 0
Reputation: 769
You need not check the device size because we can use the collectionView width to calculate the width of the cell. Using the cell width you can calculate the height as per your need.
One more thing: You need to use UICollectionViewDelegateFlowLayout & confirm the delegate & implement method below
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
{
let padding: CGFloat = 25
let collectionViewSize = collectionView.frame.size.width - padding
return CGSize(width: collectionViewSize/2, height: 115)
}
Upvotes: 1