0

I am trying to create a function, with which I can switch the background color of a UICollectionViewCell, depending on which cell is selected and on what color gets selected. I created these two functions:

    func selectedCell (at indexPath: IndexPath) {
        let indexPathForFirstRow = indexPath
        gamePad.selectItem(at: indexPathForFirstRow, animated: false, scrollPosition: UICollectionView.ScrollPosition(rawValue: 0))
    }
 @IBAction func selectedColor(_ sender: UIButton) {
        let cell = self.selectedCell(at: IndexPath)
        cell.backgroundcolor = sender.currentTitleColor
    }

In the second function, there occurs the problem, that I can't use IndexPath or indexPath.

How can I solve this problem?

That's the error which is shown when I use IndexPath

Cannot convert value of type 'IndexPath.Type' to expected argument type 'IndexPath'

That's the error which is shown when I use indexPath

Use of unresolved identifier 'indexPath'; did you mean 'IndexPath'?

Just4School
  • 117
  • 1
  • 1
  • 9
  • 3
    In your first function you are passing in an indexPath to use `func selectedCell (at indexPath: IndexPath)` but you aren't in the second one. `IndexPath` used in the second one is a Type. not a value – Scriptable Oct 02 '18 at 07:27
  • The second function is not a collectionView, these are just button with the different colors. Is this possible then? – Just4School Oct 02 '18 at 07:34
  • 2
    You need to understand difference between type and instance – SPatel Oct 02 '18 at 07:40
  • Have a look at [how to get the indexpath.row when a button in a cell is tapped?](https://stackoverflow.com/questions/28659845/swift-how-to-get-the-indexpath-row-when-a-button-in-a-cell-is-tapped) for various solutions to your problem. – Martin R Oct 02 '18 at 07:40
  • `IndexPath` is one type container – SPatel Oct 02 '18 at 07:41

1 Answers1

0

You need write a protocol. You can implement my code for your response. You have to define which indexpath in selectedColor.

// CUSTOM CELL

protocol colorDelegate {

    func changeColor(sender : CustomCell)

}

class CustomCell: UICollectionViewCell {

    var delegate:colorDelegate?

    @IBAction func selectionButtonTapped(_ sender: Any) {

        if delegate != nil {

            delegate?.changeColor(sender: self)

        }
    }


}

// VIEW CONTROLLER

@objc func changeColor(sender: CustomCell) {
    if let indexpath = tableView.indexPath(for: sender) {

        let cell = tableView.cellForRow(at: indexpath) as! CustomCell
        cell.backgroundcolor = .white

   }
} 
Ali Ihsan URAL
  • 1,894
  • 1
  • 20
  • 43