how to use custom cell in collection view controller in swift 3 - ios

I am using swift 3 - I know how to show some Images in collection view with custom Cell - the problem is that I can't use custom cell in Collection View Controller
here is the collection view Controller Codes
private let reuseIdentifier = "uploadCell"
class uploadedFiles: UICollectionViewController {
var images = ["1.jpg" , "2.jpg" , "3.jpg" , "4.jpg" ]
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)
//myCollectionView.sizeToFit()
//cell.sizeToFit()
cell.cellImages.image = UIImage(named: images[indexPath.row])
return cell
}
and here is the Collection view Cell Code
import UIKit
class UICollectionViewCell: UICollectionViewCell {
#IBOutlet weak var cellImages: UIImageView!
}
remember that I used "uploadCell" for identifier

For using CollectionView Custom Cell
Step 1: Create Subclass of CollectionViewCell
class ImageCell: UICollectionViewCell {
#IBOutlet weak var imgView: UIImageView!
}
Step 2: set CollectionViewCell class in StoryBoard
Step 3: reuseCollectionView Cell
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImageCell", for: indexPath) as! ImageCell
cell.imgView.image = self.arrMedia[indexPath.row] as? UIImage
return cell
}

UICollectionView implementation is quite interesting. You can quite simple source code and video tutorial from these link :
https://github.com/Ady901/Demo02CollectionView.git
https://www.youtube.com/watch?v=5SrgvZF67Yw
class DummyCollectionCell: UICollectionViewCell {
#IBOutlet weak var userImageView: UIImageView!
#IBOutlet weak var titleLabel: UILabel!
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "DummyCollectionCell", for: indexPath) as! DummyCollectionCell
cell.titleLabel.text = nameArr[indexPath.row]
cell.userImageView.backgroundColor = .blue
return cell
}

Related

Add title to CollectionViewCell

I have a collection view inside a table view. What I want to do next is to set a title to each of the cells inside the collection view.
I have this code inside the ViewController
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath) as! CollectionViewCell
cell.titleLabel.text = "123"
return cell;
}
This is the cell class
class CollectionViewCell: UICollectionViewCell {
#IBOutlet weak var titleLabel: UILabel!
}
When I try to add a label inside the cell and then use this label to set the title to it nothing is displayed inside the cell.
This is my current stack:
What am I doing wrong here?

UICollctionView didSelectItemAt problems

I am trying to change an UIImage in the collectionviewcell with the help of on didSelectItemAt. It is working when I select cell on the beginning but when I scroll down and scroll back up the images are back to what they were and changed images shift to different cells.
First cell selected Image
Scrolled down then came up Image
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collection_cell", for: indexPath) as! RateCardCollectionViewCell
let tempString = "\(NSLocalizedString("base_url", comment: ""))\(itemImageLink[indexPath.row])"
let urlnew:String = tempString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!
let url = URL(string: urlnew)
cell.rateCardImage.kf.setImage(with: url,placeholder: UIImage(named: "Junkart_Bin.png"))
cell.label.text = itemName[indexPath.row]
cell.itemRate.text = itemRate[indexPath.row]
cell.layer.cornerRadius = 3
cell.card.backgroundColor = UIColor.white
cell.card.layer.masksToBounds = false
cell.card.layer.shadowColor = UIColor.black.withAlphaComponent(0.2).cgColor
cell.card.layer.shadowOffset = CGSize(width: 0, height: 0)
cell.card.layer.shadowOpacity = 1 //0.8
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath) as! RateCardCollectionViewCell
if self.selectedRate == nil {
cell.changeImagetoSelected()
self.selectedRate = [Int]()
self.selectedRate.append(indexPath.row)
}
else {
}
}
Following is the UICollectionViewCell Class
class RateCardCollectionViewCell: UICollectionViewCell {
#IBOutlet weak var label: UILabel!
#IBOutlet weak var rateCardImage: UIImageView!
#IBOutlet weak var card: UIView!
#IBOutlet weak var itemRate: UILabel!
#IBOutlet weak var selected_rate_image: UIImageView!
func changeImagetounSelected() {
selected_rate_image.image = UIImage(named: "unselected_rate")
}
func changeImagetoSelected() {
selected_rate_image.image = UIImage(named: "selected_rate")
}
}
Please Help!!
Check the cell creation index added on the selectedRate at the time of cell creation cellForItemAt.
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collection_cell", for: indexPath) as! RateCardCollectionViewCell
// Your remaining codes are here.
if selectedRate.contains(IndexPath.row) {
cell.changeImageToSelected()
} else {
cell.changeImageTounselected()
}
return cell
}
This happened because collection view dequeue his cells. So you need to persist your selection in dataModel and get if cell is selected or no from it. So persist your selectedIndex in your viewController and in your cellForItemAt method call:
if(self.selectedIndex == indexPath.row){
cell.changeImageToSelected()
}
else{
cell.changeImageTounselected()
}
This will persist your selection when scroll

Outlet is nil in UICollectionViewCell

I have a UICollectionViewCell defined like so:
import UIKit
class GalleryCellCollectionViewCell: UICollectionViewCell {
#IBOutlet weak var image: UIImageView!
}
Xcode put this in automatically when I added the outlet. In my UICollectionViewController's
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
function, I then try to set an image. My code is
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! GalleryCellCollectionViewCell
let imagePackage = imagePackages?[indexPath.item]
let uiImage = imagePackage?.getUIImage()
cell.image.image = uiImage
return cell
}
In my variable viewer for the debugger, I can see that uiImage is not nil. However, cell.image is nil. Why would this be? Did I not link it up correctly in the storyboard?
You can access image with another approach using tag.
from Interface builder (IB) of the cell go to attribute tab (third tab) and set tag for the image (like 5)
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! GalleryCellCollectionViewCell
let imagePackage = imagePackages?[indexPath.item]
let uiImage = imagePackage?.getUIImage()
var cellImg:UIImageView = cell!.viewWithTag(5) as! UIImageView;
cellImg.image = uiImage
return cell
}

Collection view cell doesn't recognize its outlet

I have a collection view controller ItemCollectionVC, I want to populate its cells with images, this is how I set it:
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)
cell.cellImage.image = dataSourceItems[indexPath.row].image
// Error
return cell
}
Hoever, there's an error: Value of type UICollectionViewCell have no
member cellImage
The cell is of custom cell ItemCell, I set its custom class in story board, and here is ItemCell:
class ItemCell: UICollectionViewCell {
#IBOutlet weak var cellImage: UIImageView!
}
I also connected the outlet to the image view of the cell.
So I don't understand why there's an error, anybody knows?
Just one mistake that you need to define class for cell as! ItemCell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! ItemCell

UICollectionViewCell. I want to add 2 different picture cells

import UIKit
let reuseIdentifier = "MyCell"
class ViewController: UIViewController, UICollectionViewDataSource {
var myimage = UIImage(named: "1433584709_clock_ios7_ios_7")
#IBOutlet weak var collectionView: UICollectionView!
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CollectionViewCell
cell.imageView.image = myimage
return cell
}
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView.collectionViewLayout = CollectionViewLayout()
self.collectionView.registerClass(CollectionViewCell.self, forCellWithReuseIdentifier: "MyCell")
// Do any additional setup after loading the view, typically from a nib.
}
}
I have this code to add so many cells with same image.
However, I want to make cells to have different pictures.
Please tell me how to do this.
Use array of images instead of var myImage because collection view or tableview need some form of list or array to store all items. The indexPath.row will return the index of the images the collectionview is looking for. i.e.
var images: [String] = ["image1", "image2"]
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CollectionViewCell
cell.imageView.image = UIImage(named: self.images[indexPath.row])
return cell
}
Also in function collectionView:numberOfItemsInSection:
return self.images.count
Here is the complete code assuming you have a custom CollectionViewCell class
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
#IBOutlet weak var collectionView: UICollectionView!
var images : [String] = ["image1", "image2"]
private let reuseIdentifier = "MyCell"
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView.registerClass(CollectionViewCell.self, forCellWithReuseIdentifier: "MyCell")
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CollectionViewCell
cell.imageView.image = UIImage(named: self.images[indexPath.row])
return cell
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.images.count
}
}
Where are your images coming from?
Suppose I have a 2D array of images like myImageArray[][], then change line:
cell.imageView.image = myImage
to
cell.imageView.image = myImageArray[indexPath.section][indexPath.row]

Resources