How to change Image view in collection view cell - ios

I created an imageView in a collection view cell this way:
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath)
let imageView: UIImageView = UIImageView(image: UIImage(named: "image"))
cell.contentView.addSubview(imageView)
return cell
}
The collection view has 2 cells, now I need to change the image of the first cell to Batman and the second to Superman, how should I achieve it?

First of all you shouldn't add subviews in cellForRowAtIndexPath. These code should be in creation of your custom cell.
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath)
switch(indexPath.row) {
case 1: cell.imageView.image = UIImage(named: "batman")!
case 2: cell.imageView.image = UIImage(named: "superman")!
default: cell.imageView.image = UIImage(named: "placeholder")!
}
return cell
}

You need compare indexPath.row
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! CustomCell
var image = UIImage(named: "Superman")!
if indexPath.row == 0 {
image = UIImage(named: "Batman")!
}
cell.imageView.image = image!
return cell
}
Create your subclass of UICollectionViewCell
class CustomCell: UICollectionViewCell {
#IBOutlet var imageView : UIImageView!
override func prepareForReuse() {
super.prepareForReuse()
imageView.image = nil
}
}
And in viewDidLoad method
func viewDidLoad() {
collectionView.registerClass(CustomCell.self, forCellWithReuseIdentifier: "CustomCell")
}

You can try this code, I hope this works for you
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cellIdentifier", forIndexPath: indexPath)
var imageView: UIImageView? = cell.contentView.viewWithTag(1111) as? UIImageView
if (imageView != nil) {
//switch/case, if/else whatever you want to set images accordingly
imageView!.image = UIImage(named: "image")
} else {
imageView = UIImageView()
imageView!.tag = 1111
cell.contentView.addSubview(imageView!)
}
return cell

Thank you all for the answers! But the above answers are either a little complicated, or not working on my side, so I'm giving my own solution, inspired by #HDT:
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath)
if cell.contentView.subviews.count != 0 {
cell.contentView.subviews[0].removeFromSuperview()
}
switch indexPath.row {
case 0:
cell.contentView.addSubview(UIImageView(image: frontImage))
case 1:
cell.contentView.addSubview(UIImageView(image: backImage))
default:
cell.contentView.addSubview(UIImageView(image: UIImage(named: "Image")))
}
return cell
}

Related

Cannot set imageView in CollectionViewCell

In my code, I am trying to set the imageView of a UICollectionViewCell. The imageView is called cellImageView in the CollectionViewCell class. When the app loads up it tries to initialize this value, but it doesn't work
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "selectCell", for: indexPath) as! PhraseSelectionCell
cell.cellImageView?.image = UIImage(named: "lol")
return cell
}
Class of UICollectionViewCell
class PhraseSelectionCell: UICollectionViewCell {
#IBOutlet var cellImageView: UIImageView!
}
try debugging this way, then you can find where the bug is.
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "selectCell", for: indexPath) as! PhraseSelectionCell
//debug 1
if UIImage(named: "lol") == nil {
print("image is nil, double check image name")
}
//debug 2
if cell.cellImageView == nil {
print("cellImageView outlet is nil")
}
cell.cellImageView?.image = UIImage(named: "lol")
return cell
}

Cells don't show up in a table view until minimal scrolling or tap (NOTE: nothing happens on a background thread)

I have a horizontally scrollable UICollectionView with three cells each of which are different subclasses of UICollectionViewCell. Each one of these cells contains a UITableView.
Inside of the first two cells, my table view cells are the same subclasses of UITableViewCell and have just a UIImageView. I use it to set its backgroundColor. Inside of the third cell, my table view's cells are different subclasses of UITableViewCell than in the previous two. They have both a UILabel and a UIImageView. The label has some dummy text, and I set imageView's backgroundColor to some color, again.
In order to follow MVC pattern, I use my UIViewController as a data source and a delegate for both collection view, and table view. Here is the code of UIViewController:
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
let collectionViewCellId = "collectionViewCell"
let tableViewCellId = "tableViewCell"
let collectionViewCellId2 = "collectionViewCellId2"
let collectionViewCellId3 = "collectionViewCellId3"
let tableViewCellDif = "tableViewCellDif"
var collectionViewIndex: Int?
#IBOutlet weak var collectionView: UICollectionView! {
didSet {
collectionView.delegate = self
collectionView.dataSource = self
collectionView.isPagingEnabled = true
}
}
//MARK: UITableViewDataSource
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let colors: [UIColor] = [.red, .green, .purple, .orange, .blue]
let colors2: [UIColor] = [.blue, .brown, .yellow, .magenta, .cyan]
if collectionViewIndex == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: tableViewCellId, for: indexPath) as! TableViewCell
cell.colorForImageView = colors[indexPath.row]
return cell
} else
if collectionViewIndex == 1 {
let cell = tableView.dequeueReusableCell(withIdentifier: tableViewCellId, for: indexPath) as! TableViewCell
cell.colorForImageView = colors2[indexPath.row]
return cell
} else
if collectionViewIndex == 2 {
let cell = tableView.dequeueReusableCell(withIdentifier: tableViewCellDif, for: indexPath) as! TableViewCellDifferent
cell.colorForImageView = colors2[indexPath.row]
return cell
} else {
return UITableViewCell()
}
}
}
//MARK: UICollectionViewDataSource
extension ViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 3
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let identifier: String
if indexPath.item == 0 {
identifier = collectionViewCellId
} else if indexPath.item == 1 {
identifier = collectionViewCellId2
} else if indexPath.item == 2 {
identifier = collectionViewCellId3
} else {
identifier = ""
}
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath)
return cell
}
}
//MARK: UICollectionViewDelegate
extension ViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
if indexPath.item == 0 {
let cell = cell as! CollectionViewCell
cell.tableView.dataSource = self
cell.tableView.delegate = self
collectionViewIndex = 0
}
if indexPath.item == 1 {
let cell = cell as! CollectionViewCell2
cell.tableView.dataSource = self
cell.tableView.delegate = self
collectionViewIndex = 1
}
if indexPath.item == 2 {
let cell = cell as! CollectionViewCell3
cell.tableView.dataSource = self
cell.tableView.delegate = self
collectionViewIndex = 2
print (collectionViewIndex)
}
}
}
//MARK: UICollectionViewDelegateFlowLayout
extension ViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let layout = collectionViewLayout as! UICollectionViewFlowLayout
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
return CGSize(width: collectionView.frame.width, height: collectionView.frame.height)
}
}
As I stated in a title of the question, nothing happens on a background thread. I, basically, only set the backgroundColor of table view's cells.
The problem is that inside the collection view's third cell (and only inside of there), my table view dequeues its cells only after a minor scroll or tap happens. Here is how it looks like:
I can't figure out why this happens. Maybe, this happens because inside of the third cell of the collection view, my table view's cells are instances of different subclass than inside of the first two?
EDITED
I could solve the problem by reloading the table view before before showing the collection view's each cell but I'm not sure that this is the most efficient solution. Here is the code:
//MARK: UICollectionViewDelegate
extension ViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
if indexPath.item == 0 {
let cell = cell as! CollectionViewCell
cell.tableView.dataSource = self
cell.tableView.delegate = self
cell.tableView.reloadData()
collectionViewIndex = 0
}
if indexPath.item == 1 {
let cell = cell as! CollectionViewCell2
cell.tableView.dataSource = self
cell.tableView.delegate = self
cell.tableView.reloadData()
collectionViewIndex = 1
}
if indexPath.item == 2 {
let cell = cell as! CollectionViewCell3
cell.tableView.dataSource = self
cell.tableView.delegate = self
cell.tableView.reloadData()
collectionViewIndex = 2
}
}
}
If you know a better way, I would appreciate your help.
I gave this a try, and saw the same results. So, I moved your collection view cell "setup" code from willDisplay cell: to cellForItemAt and it fixed the problem.
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if indexPath.item == 0 {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: collectionViewCellId, for: indexPath) as! CollectionViewCell
cell.tableView.dataSource = self
cell.tableView.delegate = self
collectionViewIndex = 0
return cell
}
if indexPath.item == 1 {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: collectionViewCellId2, for: indexPath) as! CollectionViewCell2
cell.tableView.dataSource = self
cell.tableView.delegate = self
collectionViewIndex = 1
return cell
}
// if we get here, indexPath.item must equal 2
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: collectionViewCellId3, for: indexPath) as! CollectionViewCell3
cell.tableView.dataSource = self
cell.tableView.delegate = self
collectionViewIndex = 2
return cell
}
Now, since you're not showing your code for your tableview cells, it's possible there might be another issue, but this worked for me:
class TableViewCell: UITableViewCell {
#IBOutlet var theImageView: UIImageView!
var colorForImageView: UIColor = UIColor.gray {
didSet {
self.theImageView.backgroundColor = colorForImageView
}
}
}
You can try to dequeue CollectionViewCell or TableViewCell explicitly on the main thread
DispatchQueue.main.async {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath)
}
or
DispatchQueue.main.async {
let cell = tableView.dequeueReusableCell(withIdentifier: tableViewCellDif, for: indexPath) as! TableViewCellDifferent
cell.colorForImageView = colors2[indexPath.row]
}
It could help to wake up the main thread
But in general, it would be much easier if a data source for the table view was inside collection view cell

How to hide lock image from row 0 in UICollectionView when Scrolling swift3

I have a UICollectionView, it is working perfect. I added lock image on all row except row 0. When ViewController is loaded,it is working fine but when i scroll it horizontally, it is showing lock image on row 0. what i am doing wrong? Thanks in advace.
Here is my code:-
var imageView1 = UIImageView()
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath) as! CollectionViewCell
cell.label.text = tittle[indexPath.row]
cell.imageView.image = UIImage(named : image[indexPath.row] )
imageView1 = UIImageView(frame:CGRect(x :cell.frame.size.width / 2 - 30 ,y : 40, width : 30, height : 30));
imageView1.image = UIImage(named: "lock.png")
imageView1.image = imageView1.image!.withRenderingMode(.alwaysTemplate)
imageView1.tintColor = UIColor.white
if (indexPath.row == 0) {
imageView1.isHidden = true
imageView1.removeFromSuperview()
} else {
cell.imageView.addSubview(imageView1)
if (RemoteModel.sharedInstanceRemoteModel.purchased){
imageView1.isHidden = true
} else {
imageView1.isHidden = false
}
}
return cell
}
Here you are using the custom collection view cell which is CollectionViewCell
So try adding that in your custom cell xib or story board prototype cell wherever you have designed it
and then connnect it to outlet
and after that try hiding/unhiding that image view according to the condition
And initially try keeping it hidden in xib or story board
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath) as! CollectionViewCell
cell.label.text = tittle[indexPath.row]
cell.imageView.image = UIImage(named : image[indexPath.row] )
if (indexPath.item == 0)
{
cell.imageView1.isHidden = true
}
else
{
if (RemoteModel.sharedInstanceRemoteModel.purchased)
{
cell.imageView1.isHidden = true
}
else
{
cell.imageView1.isHidden = false
}
}
return cell
}
You are adding the UIImageView imageView1 in cell.imageView with this method cell.imageView.addSubview(imageView1)
If you are adding this directly into the cell you need to remove from its superview, because imageView1 don't have the reference from the previous cell, we are use the cell reuse.
For Either you can go with the above solution or you need to add the lock image in for custom Cell and maintain the hide/show in:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
You should be adding lock image view in your storyboard but if you want to add it from code, You should be adding lock image view in your CollectionViewCell and just hide/unhide it from cellForItemAt. I suppose your cell is designed in storyboard or nib.
class CollectionViewCell : UICollectionViewCell {
var lockImageView: UIImageView?
override func awakeFromNib() {
lockImageView = UIImageView(frame:CGRect(x :self.frame.size.width / 2 - 30 ,y : 40, width : 30, height : 30));
lockImageView?.image = UIImage(named: "lock.png")!.withRenderingMode(.alwaysTemplate)
lockImageView.tintColor = UIColor.white
self.contentView.addSubview(lockImageView!)
}
}
And in cellForItemAt just hide/unhide.
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath) as! CollectionViewCell
cell.label.text = tittle[indexPath.row]
cell.imageView.image = UIImage(named : image[indexPath.row] )
if (indexPath.row == 0) {
cell.lockImageView.isHidden = true
} else {
if (RemoteModel.sharedInstanceRemoteModel.purchased){
cell.lockImageView.isHidden = true
} else {
cell.lockImageView.isHidden = false
}
}
return cell
}
It's not efficient to added views and remove within cellForItemAt method. And also you are not supposed to add views in UIImageView.
This is working for me, I added small image, on image view from storyboard, than make initially hide it, than put the lock image image on it, it is working.
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath) as! CollectionViewCell
cell.label.text = tittle[indexPath.row]
cell.imageView.image = UIImage(named : image[indexPath.row] )
imageView1 = UIImageView(frame:CGRect(x :cell.frame.size.width / 2 - 30 ,y : 40, width : 30, height : 30));
cell.lockiconmindcultivation.isHidden = false
cell.lockiconmindcultivation.image = UIImage(named: "lock.png")
cell.lockiconmindcultivation.image = cell.lockiconmindcultivation.image!.withRenderingMode(.alwaysTemplate)
cell.lockiconmindcultivation.tintColor = UIColor.white
if (indexPath.row == 0){
cell.lockiconmindcultivation.isHidden = true
}
cell.lockiconmindcultivation.isHidden = false
cell.lockiconmindcultivation.image = UIImage(named: "lock.png")
cell.lockiconmindcultivation.image = cell.lockiconmindcultivation.image!.withRenderingMode(.alwaysTemplate)
cell.lockiconmindcultivation.tintColor = UIColor.white
if (RemoteModel.sharedInstanceRemoteModel.purchased){
cell.lockiconmindcultivation.isHidden = true
}else{
cell.lockiconmindcultivation.isHidden = false
}
}
return cell
}

I have checkbox image in UICollectionViewCell which I want to show as selected or unselected?

I want to select all and deselect all cell of collectionView using select All and deselect all UIButton?
Please help anyone.
//Delegate Method cellForItemAtIndexPath
func collectionView(collectionView: UICollectionView,
cellForItemAtIndexPath indexPath: NSIndexPath) ->
UICollectionViewCell
{
//Get a reference to our storyboard cell
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(
"pickSomecell",
forIndexPath: indexPath) as! pickSomeGridViewController
//Show Images in grid view
cell.cellImage.image = self.arrAllOriginalImages[indexPath.row] as? UIImage
cell.toggleSelected()
//return cell.
return cell
}
Thanks
try to do as follow-
var isSelectAll=false
func collectionView(collectionView: UICollectionView,
cellForItemAtIndexPath indexPath: NSIndexPath) ->
UICollectionViewCell
{
//Get a reference to our storyboard cell
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(
"pickSomecell",
forIndexPath: indexPath)
//Show Images in grid view
if isSelectAll {
cell.cellImage.image = selectedImage;
}else{
cell.cellImage.image = desselectedImage;
}
return cell
}
#IBAction func selectAllcell(sender: AnyObject) {
isSelectAll=true
collectionView.reloadData()
}
#IBAction func deselectAllcell(sender: AnyObject) {
isSelectAll=false
collectionView.reloadData()
}

How to show check tick mark in Collection view (images)

In Table view we can put checkmark easily on cells.
But in Collection View how can we put check mark, when we select a cell (image)?
I just took a image view inside the cell and image view and put a tick mark image. My code is below.
But it's not working.
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)
{
// handle tap events
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! customCollectionViewCell
if(cell.checkMarkImage.hidden == true)
{
print("Hidden")
cell.checkMarkImage.hidden = false
}
else
{
cell.checkMarkImage.hidden = true
print("No Hidden")
}
}
//Delegate Method cellForItemAtIndexPath
func collectionView(collectionView: UICollectionView,
cellForItemAtIndexPath indexPath: NSIndexPath) ->
UICollectionViewCell
{
//Get a reference to our storyboard cell
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(
"pickSomecell",
forIndexPath: indexPath) as! pickSomeGridViewController
//Show Images in grid view
cell.cellImage.image = self.arrAllOriginalImages[indexPath.row]
as? UIImage
//Check Mark toggle.
cell.toggleSelected()
//return cell.
return cell
}
And in pickSomeGridViewController show checkMark image selected or not.
class pickSomeGridViewController: UICollectionViewCell{
//Outlet of cell image.
#IBOutlet var cellImage: UIImageView!
//Outlet of checkMark image.
#IBOutlet var cellCheckMarkImage: UIImageView!
//Function for select and deselect checkmark.
func toggleSelected ()
{
//If image is selected.
if (selected)
{
//Show check mark image.
self.cellCheckMarkImage.hidden = false
}
else
{
//Hide check mark image.
self.cellCheckMarkImage.hidden = true
}
}
}
I see two main problems with this code:
You use dequeueReusableCellWithReuseIdentifier method which obtains different cell from collection view cache, not the one on screen.
Use cellForItemAtIndexPath method of collection view instead.
You try to save cell's state (selected/not selected) in the cell itself. It's common mistake when working with UITableView/UICollectionView and this approach will not work. Instead, keep the state in some other place (in dictionary, for example) and restore it every time collection view calls your data source cellForItemAtIndexPath method.
var arrData = NSMutableArray()
// 1.Make a ModalClass.swift and NSArray with modal class objects like this
class CustomModal: NSObject {
//Declare bool variable for select and deselect login
var is_selected = Bool()
//you can declare other variable also
var id = Int32()
}
// 2. custom array with modal objects
override func viewDidLoad() {
super.viewDidLoad()
let arrTemp = NSArray()
arrTemp = [1,2,3,4,5,6,7,8,9,10]
for i in 0 ..< arrTemp.count{
let eventModal = CustomModal()
eventModal.is_selected = false
eventModal.id = arrTemp[i]
arrData.add(eventModal)
}
tblView.reloadData()
}
// 2. Use collection view delegate method
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let modal = arrData[indexPath.row] as! CustomModal()
modal.is_selected = true
self.arrData.replaceObject(at: indexPath.row, with: modal)
tblView.reloadData()
}
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
let modal = arrData[indexPath.row] as! CustomModal()
modal.is_selected = false
self.arrData.replaceObject(at: indexPath.row, with: modal)
tblView.reloadData()
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! YourCellClass
let modal = arrData[indexPath.row] as! CustomModal
if modal.is_selected == true{
cell.imgView.image = UIImage(named:"selected_image")
}else{
cell.imgView.image = UIImage(named:"deselected_image")
}
}
#Kishor, paintcode is the third party tool through which you can do that. I have provided the link too. since by default you don't have this facility, you should make your custom behavior to achiever this. Thanks.
Swift 4
In ViewController
// make a cell for each cell index path
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "YourCollectionViewCellID", for: indexPath as IndexPath) as! YourCollectionViewCell
cell.someImageView.image = imgArr[indexPath.item]
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print("You selected cell #\(indexPath.item)!")
let cell = collectionView.cellForItem(at: indexPath) as? YourCollectionViewCell
cell?.isSelected = true
cell?.toggleSelected()
}
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath) as? YourCollectionViewCell
cell?.isSelected = false
cell?.toggleSelected()
}
In YourCollectionViewCell
class YourCollectionViewCell: UICollectionViewCell {
#IBOutlet weak var someImageView: UIImageView!
#IBOutlet weak var checkImageView: UIImageView!
//Function for select and deselect checkmark.
public func toggleSelected() {
if (isSelected == false) {
//Hide check mark image.
self.checkImageView.image = UIImage(named: "unCheckImage")
isSelected = true
}else{
//Show check mark image.
self.checkImageView.image = UIImage(named: "CheckImage")
isSelected = false
}
}
}
Hope enjoy!!
var selectedCellIndex:Int?
take variable if you want to show selected Item after reloadData() : which is previously selected CellItem. {inspired by above answer }
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ColorCollectionCell", for: indexPath) as! ColorCollectionCell
cell.isSelected = false
if selectedCellIndex == indexPath.item {
cell.checkMarkImgView.image = UIImage(named: "icn_checkMark")
}else {
cell.toggleSelected()
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath) as! ColorCollectionCell
cell.isSelected = true
selectedCellIndex = indexPath.item
cell.toggleSelected()
}
In CollectionViewCell u can use this method
class ColorCollectionCell: UICollectionViewCell {
#IBOutlet weak var cellimgView: UIImageView!
#IBOutlet weak var checkMarkImgView: UIImageView!
func toggleSelected() {
if (isSelected) {
self.checkMarkImgView.image = UIImage(named: "icn_checkMark")
}else{
self.checkMarkImgView.image = UIImage(named: "")
// here you can use uncheck img here i am not using any image for not selected.
}
}
}

Resources