UICollectionView - Mutiple& Swift4在不同部分进行单一选择

时间:2018-02-05 08:40:01

标签: ios swift uicollectionview uicollectionviewcell

我想在UICollectionView中进行多项选择,我有五个部分有不同的选择设置。
我想在第1节和第2节中进行单一选择 以及第0,3和4节中的多项选择 当我单击两次相同的项目时,它将取消选择该项目 但是,当我单击单个部分项目时,它将取消先前选择的项目并选择单击的项目。

我按照我在UITableView中成功完成的另一个答案,但我不知道如何在UICollectionView中完美地完成这项工作?
感谢。

var collectionView: UICollectionView!
var selectArray: [IndexPath] = []

func collectionViewSetting(){
    collectionView.delegate = self
    collectionView.dataSource = self
    collectionView.alwaysBounceVertical = true
    collectionView.backgroundColor = UIColor.lightGray
    collectionView.allowsMultipleSelection = true
    self.view.addSubview(collectionView)
}


func numberOfSections(in collectionView: UICollectionView) -> Int {
    let count = 5
    return count
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 10
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let key = Array(conditionsDictionary.keys)[indexPath.section]
    let array: [String] = conditionsDictionary[key]!

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell
    cell.label.text = "12345"

    return cell
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let cell = collectionView.cellForItem(at: indexPath)
    cell?.backgroundColor = UIColor.orange
    selectArray.append(indexPath)
}

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

    let cell = collectionView.cellForItem(at: indexPath)
    cell?.backgroundColor = UIColor.clear

    if let index = selectArray.index(of:indexPath) {
        selectArray.remove(at: index)
    }
}

print(selectArray)

1 个答案:

答案 0 :(得分:3)

根据您的要求,我准备了一个正常运行的示例代码。

Swift 4

    //
    //  ViewController.swift
    //  SOCollectionSelectionHandling
    //
    //  Created by Test User on 05/02/18.
    //  Copyright © 2018. Ltd. All rights reserved.
    //

    import UIKit

    class ViewController: UIViewController {

        var collectionView: UICollectionView!
        var selectArray : [IndexPath] = []
        let sections  = 5
        let cell = "MyCell"

        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a nib.
            setUpCollectionViewAndSettings()
        }

        func setUpCollectionViewAndSettings() {

            let layout = UICollectionViewFlowLayout()
            layout.itemSize = CGSize.init(width: 50, height:  50)
            collectionView = UICollectionView.init(frame: self.view.frame , collectionViewLayout: layout)
            collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: cell)
            collectionView.alwaysBounceVertical = true
            collectionView.backgroundColor = UIColor.lightGray
            collectionView.delegate = self
            collectionView.dataSource = self
            collectionView.allowsMultipleSelection = true

            self.view.addSubview(collectionView)
        }
    }

    //MARK: Collection View Delegate and DataSource Methods

    extension ViewController : UICollectionViewDelegate , UICollectionViewDataSource {

        //MARK: Collection Data  Source
        func numberOfSections(in collectionView: UICollectionView) -> Int {
            return sections
        }

        func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
            return 10
        }

        func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: self.cell, for: indexPath)
            if selectArray.count > 0 {
                selectArray.forEach { (selectedIndex) in
                    if (selectedIndex.section == indexPath.section && selectedIndex.row ==  indexPath.row) { // Change Color of selected Index
                        if (selectedIndex.section == 0 || selectedIndex.section == 3 || selectedIndex.section == 4) {
                            DispatchQueue.main.async {
                                let cell = collectionView.cellForItem(at: selectedIndex)
                                cell?.backgroundColor = UIColor.orange
                            }
                        } else {
                            cell.backgroundColor = UIColor.yellow
                        }
                    }
                    else { //Set Default Color of Not Selected Index
                        if indexPath.section == 0 || indexPath.section == 3 || indexPath.section == 4 {
                            cell.backgroundColor = UIColor.blue
                        } else {
                            cell.backgroundColor = UIColor.red
                        }
                    }
                }
            } else {
                if indexPath.section == 0 || indexPath.section == 3 || indexPath.section == 4 {
                    collectionView.allowsMultipleSelection = true
                    cell.backgroundColor = UIColor.blue
                } else {
                    collectionView.allowsMultipleSelection = false
                    cell.backgroundColor = UIColor.red
                }
            }
            return cell
        }

        //MARK: Collection Delegate for Selection and Deselection

        func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
            let cell = collectionView.cellForItem(at: indexPath)
            if indexPath.section == 0 || indexPath.section == 3 || indexPath.section == 4 {
                self.handleMultipleSelection (collectionView: collectionView ,cell : cell! , indexPath : indexPath )
            } else {
                selectArray.removeAll()
                collectionView.allowsMultipleSelection = false
                cell?.backgroundColor = UIColor.yellow
                selectArray.append(indexPath)
                print(selectArray)
                collectionView.reloadData()
            }
        }



        func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
            let cell = collectionView.cellForItem(at: indexPath)

            if indexPath.section == 0 || indexPath.section == 3 || indexPath.section == 4 {
                self.handleMultipleDeSelection(collectionView: collectionView
                    , cell: cell!, indexPath: indexPath)
            } else {
                //Remove all selected record from array for Single Selection
                selectArray.removeAll()
                cell?.backgroundColor = UIColor.red
            }
            collectionView.reloadData()
        }


        //MARK: Multiple Selection Handle Method

        func handleMultipleDeSelection(collectionView: UICollectionView
            , cell: UICollectionViewCell, indexPath: IndexPath) {
            // Remove Previous Selected Cell Record from Array at time of Section Switching
            if selectArray.count > 0 {
                selectArray.forEach({ (path) in
                    if (path.section == indexPath.section) {
                        if let index = selectArray.index(of : path) {
                            let cell = collectionView.cellForItem(at: path)
                            if path.section == 0 || path.section == 3 || path.section == 4 {
                                cell?.backgroundColor = UIColor.blue
                            } else {
                                cell?.backgroundColor = UIColor.red
                            }
                            selectArray.remove(at:index)
                        }
                    }
                })
            }
            cell.backgroundColor = UIColor.blue
            if let index = selectArray.index(of:indexPath) {
                selectArray.remove(at: index)
                print(selectArray)
            }
            else {
                //Removing Unwanted Section from array
                if selectArray.count > 0 {
                    selectArray.forEach({ (path) in
                        if (path.section == 1 || path.section == 2) {
                            if let index = selectArray.index(of: path) {
                                let cell = collectionView.cellForItem(at: path)
                                cell?.backgroundColor = UIColor.red
                                selectArray.remove(at:index)
                            }
                        }
                    })
                }
                //Adding Selected cell in Selection Array
                selectArray.append(indexPath)
                print(selectArray)
                collectionView.reloadData()
            }
        }


        func handleMultipleSelection (collectionView: UICollectionView ,cell : UICollectionViewCell , indexPath : IndexPath )  {
            // Remove Previous Selected Cell Record from Array at time of Section Switching
            if selectArray.count > 0 {
                selectArray.forEach({ (path) in
                    if (path.section != indexPath.section) {
                        if let index = selectArray.index(of : path) {
                            let cell = collectionView.cellForItem(at: path)
                            if path.section == 0 || path.section == 3 || path.section == 4 {
                                cell?.backgroundColor = UIColor.blue
                            } else {
                                cell?.backgroundColor = UIColor.red
                            }
                            selectArray.remove(at:index)
                        }
                    }
                })

            }

            collectionView.allowsMultipleSelection = true
            cell.backgroundColor = UIColor.orange

            if let index = selectArray.index(of:indexPath) {
                selectArray.remove(at: index)
                print(selectArray)
                collectionView.reloadData()
            } else {
                //Removing Unwanted Section from array
                if selectArray.count > 0 {
                    selectArray.forEach({ (path) in
                        if (path.section == 1 || path.section == 2) {
                            if let index = selectArray.index(of: path) {
                                let cell = collectionView.cellForItem(at: path)
                                cell?.backgroundColor = UIColor.red
                                selectArray.remove(at:index)
                            }
                        }
                    })
                }

                //Adding Selected cell in Selection Array
                selectArray.append(indexPath)
                print(selectArray)
                collectionView.reloadData()
            }
        }


    }