user10472859
user10472859

Reputation:

How do I got Multiple Selections in UICollection View using Swift 4

I'm new to swift and building iOS Application from the scratch (using swift 4) and want to do something like below. 1. Implement Multiple cell selections in UICollectionView, 2. Pass selected cells data to Server. Please anyone can help me, how to do that? Tell me the process and supporting articles to do that.

Below is reference Image. Thanks in Advance.

Reference Image/Screen

Upvotes: 11

Views: 24585

Answers (6)

AzeTech
AzeTech

Reputation: 707

Inside your collection view cell,

class CollectionCell: UICollectionViewCell {
    
    @IBOutlet weak var serviceLbl: UILabel!
    
    override var isSelected: Bool {
        didSet {
            if self.isSelected {
                contentView.layer.borderColor = UIColor.yellow.cgColor
                contentView.layer.borderWidth = 1
                contentView.layer.masksToBounds = true
            }
            else {
                contentView.layer.borderColor = UIColor.clear.cgColor
                contentView.layer.borderWidth = 1
                contentView.layer.masksToBounds = true
            }
        }
    } 
}

Then in controller declare,

collectionView.allowsMultipleSelection = true 

Finally, print index in didSelect

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print(collectionView.indexPathsForSelectedItems)
    }

Upvotes: 0

Rajesh Kumar Sahil
Rajesh Kumar Sahil

Reputation: 39

  • Enable Multiple Selection
    collectionView.allowsMultipleSelection = true
  • Overrider isSelected property of collectionViewCell.
    override var isSelected: Bool {
        didSet {
            if self.isSelected {
                //You can change this method according to your need.
                setSelected()
            }
            else {
                //You can change this method according to your need.
                setUnselected()
            }
        }
    }

    func setSelected(){
        bgView.layer.borderWidth = 4
        bgView.layer.borderColor = UIColor.Palette.darkBlue.cgColor
        bgView.backgroundColor = .blue.withAlphaComponent(0.2)
    }
    
    func setUnselected(){
        bgView.layer.borderWidth = 0
        bgView.backgroundColor = .white
    }
  • You can print selected cell's indexPath
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print(collectionView.indexPathsForSelectedItems)
    }

Upvotes: 2

ben khedher mahmoud
ben khedher mahmoud

Reputation: 431

Well, the best way to handle multiple selections in UICollectionView

  1. Enable Multiple Selection
myCollectionView.allowsMultipleSelection = true
  1. put this code in your cell awakeFromNib
override func awakeFromNib() {
  super.awakeFromNib()
        
  let view = UIView(frame: bounds)
  self.backgroundView = view
        
  let coloredView = UIView(frame: bounds)
  coloredView.backgroundColor = UIColor.red
  self.selectedBackgroundView = coloredView
}
  1. you can get the selected indexPath items
let items = myCollectionView.indexPathsForSelectedItems

Upvotes: 37

Saurabh
Saurabh

Reputation: 222

You can write the code like this to Enable Multiple Selection :-

yourCollectionViewName.allowsMultipleSelection = true   

then you can Do it like this to see the cell Selected -

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    var cell = collectionView.cellForItemAtIndexPath(indexPath)
    if cell?.selected == true {
        cell?.backgroundColor = UIColor.orangeColor()
    }
}

To Deselect You can do something Like this -

func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {        
   var cell = collectionView.cellForItemAtIndexPath(indexPath)
   cell?.backgroundColor = UIColor.clearColor()
}

Upvotes: 9

Kuldeep
Kuldeep

Reputation: 4552

This basic example. You can change as per your data.

When you select any cell then you need to check that selected cell is already selected before or not.

If not then add selected cell indexPath in indexArray and selected cell value in valueArray.

If current selected cell is previously selected then remove indexPath from indexArray and also remove selected cell value from valueArray

on continue button press pass arrSelectedData to server or next screen.

Define below 3 array.

var arrData = [String]() // This is your data array
var arrSelectedIndex = [IndexPath]() // This is selected cell Index array
var arrSelectedData = [String]() // This is selected cell data array

//UICollectionView Delegate & DataSource

extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout 
{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.arrData.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell : CollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath) as! CollectionViewCell

        if arrSelectedIndex.contains(indexPath) { // You need to check wether selected index array contain current index if yes then change the color
            cell.vw.backgroundColor = UIColor.red
        }
        else {
            cell.vw.backgroundColor = UIColor.lightGray
        }

        cell.layoutSubviews()
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: 100, height: 100)
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print("You selected cell #\(indexPath.item)!")

        let strData = arrData[indexPath.item]

        if arrSelectedIndex.contains(indexPath) {
            arrSelectedIndex = arrSelectedIndex.filter { $0 != indexPath}
            arrSelectedData = arrSelectedData.filter { $0 != strData}
        }
        else {
            arrSelectedIndex.append(indexPath)
            arrSelectedData.append(strData)
        }

        collectionView.reloadData()
    }
}

Upvotes: 11

Shubham Bakshi
Shubham Bakshi

Reputation: 572

Well, to achieve a thing like that, you need to mainly perform the following tasks

  1. Whenever user clicks on a particular cell, you need to change the background colour for that item in the didSelectItemAt delegate method of UICollectionView

  2. Now to send that data to server, you need an array to store all the selected cells and then send that array to server . You can perform the same in didSelectItemAt method as well

I can show you a prototype of what the function will look like:

Let's assume you have an array named arrayForPopulating for populating data inside Collection View and we have array named finalSelections which consist of names of all the selections that user made

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

   let cell = collectionView.cellForItem(at: indexPath)

   // Change the background colour of the cell here
   cell.contentView.backgroundColor = UIColor.red

   // Add the selected cell's data to the array
   finalSelections.append(arrayForPopulating[indexPath.row])

}

Now you can send you finalSelections array to the server !

Upvotes: 0

Related Questions