Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import UIKit
- //defining a enum to track cell state
- enum CellState {
- case selected
- case unselected
- init() {
- self = .unselected
- }
- }
- class yourCell: UICollectionViewCell {
- @IBOutlet weak var yourBtn: UIButton!
- // creating our func
- var buttonAction: (() -> ())?
- override func awakeFromNib() {
- super.awakeFromNib()
- }
- @IBAction func sliderAction(_ sender: UISlider) {
- // defining our func where we want to use it
- buttonAction()
- }
- }
- // inside our viewController
- import UIKit
- class yourViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
- @IBOutlet weak var collectionView: UICollectionView!
- // you data source that you fill the cells
- var yourDataArray: [yourDataSource]()
- // the array that will hold status of our cells
- private var cellStateArray: [CellState]?
- override func viewDidLoad() {
- super.viewDidLoad()
- //confirming our delegate and dataSource
- collectionView.dataSource = self
- collectionView.delegate = self
- //filling your cellStateArray as many as your cell count
- self.cellStateArray = Array(repeating: .unselected, count: self.yourDataArray!.count )
- }
- func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
- if yourDataArray?.isEmpty == false {
- return yourDataArray!.count
- } else {
- print("Caution yourDataArray IS EMPTY")
- return 0
- }
- }
- func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
- let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "yourCell", for: indexPath) as! yourCell
- // checking your button selected or not while reuse it (while scrolling)
- if cellStateArray![indexPath.row] == .selected {
- cell.yourBtn.backgroundColor = .red
- } else {
- cell.yourBtn.backgroundColor = .blue
- }
- cell.buttonAction = {
- //calling button function
- button_Select(_ sender: cell.yourBtn, cellStateArray: cellStateArray, indexPath: IndexPath)
- }
- }
- // Defining the function what you want to do with your button in each cell
- func button_Select(_ sender: UIButton, cellStateArray: [CellState], indexPath: IndexPath ) {
- sender.isSelected = !sender.isSelected
- if sender.isSelected{
- sender.backgroundColor = .red
- //setting value when your button selected
- cellStateArray[indexPath.row] = .selected
- }
- else{
- sender.backgroundColor = .blue
- //setting value when your button unselected
- cellStateArray[indexPath.row] = .unselected
- }
- collectionView.reloadData()
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement