Skip to content

Instantly share code, notes, and snippets.

@BSN4
Last active June 17, 2016 02:58
Show Gist options
  • Save BSN4/4eabc5525254179b802528f060712324 to your computer and use it in GitHub Desktop.
Save BSN4/4eabc5525254179b802528f060712324 to your computer and use it in GitHub Desktop.
custom columns UICollectionView (swift edition)
//
// Cusutom UICollectionView Coulmns , You can resize rows size .. This code made for fun no bugs for now but use it carefully
// There're other methods to accomplish this but I prefier it this way
// Created by bader almutairi on 6/11/16.
// Copyright © 2016 phpfalcon. All rights reserved.
//
import Foundation
import UIKit
class CViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
let reuseIdentifier = "cell" //storyboard
var items = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16"]
var ncoulmns : Int = 3 // number of coulmns
var cellheight : Int = 100 //cell's height
var nsc : Int = 0 //number of sections leave it blank
override func viewDidLoad() {
super.viewDidLoad()
nsc = Int(ceil(Double(self.items.count) / Double(ncoulmns)))
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - UICollectionViewDataSource protocol
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int
{
return nsc
}
// tell the collection view how many cells to make
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return (section == nsc - 1) ? ncoulmns - (((section + 1) * ncoulmns) - self.items.endIndex) : ncoulmns
}
// make a cell for each cell index path
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
// get a reference to our storyboard cell
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! cViewCell
let x = indexPath.section * ncoulmns + indexPath.row
// Use the outlet in our custom class to get a reference to the UILabel in the cell
cell.myLabel.text = self.items[x]
cell.backgroundColor = UIColor.yellowColor() // make cell more visible in our example project
return cell
}
// MARK: - UICollectionViewDelegate protocol
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
// handle tap events
print("You selected cell #\( indexPath.section * ncoulmns + indexPath.row)!")
}
func collectionView(collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return CGSizeMake(collectionView.bounds.size.width/CGFloat(ncoulmns), CGFloat(cellheight))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment