Hi,
Step's required to use collectionView in Swift
1- Add collection View in your project
2- Set the delegate for collection view in controller
3- Collection view has a prototype cell, you can design accordingly you want.
4- Create a subclass of UICollectionViewCell (You can name it as - MyCollectionViewCell).
5- Assign class to prototype cell
6- Create the outlet for the CollectionViewCell elements
7- set an identifier for the cell (For Example - "CollectionCellID")
8- Implement the following code in your ViewController Class
also, Assign a value to
let reuseIdentifier = "CollectionCellID"
9- Create an array for element like
var arrayOfelement : NSMutableArray = []
for i in 1...15 {
arrayOfelement.addObject(i)
}
//MARK : DELEGATE METHOD FOR COLLECTION VIEW
//These method are in ViewController.swift class
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return arrayOfelement.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! MyCollectionViewCell
cell.setCellData(String(arrayOfelement.objectAtIndex(indexPath.row))
return cell
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
print("selected item == \(indexPath.row)")
}
10 - In your MyCollectionVIewCell create a method setCellData (Here i have a lable in my Cell , So here i am setting the text to my Lable)
11 - Here is the code for my MyCollectionViewCell Class
class MyCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var txtlbl : UILabel?
func setCellData(text:String) -> Void {
print("Hello sdat == \(text)")
txtlbl?.text = text
}
}
0 Comment(s)