0

i have created one custom cell, in which i have one button. i want to change colour of cell on that button click (not on didSelect row). I have given tag to button in cellforrow method and called selector method.

 btnCell.tag = indexPath.row
 btnCell.addTarget(self, action: #selector(buttonClicked( sender:)),for: .touchUpInside)


func buttonClicked(sender:UIButton) {
//how can i change cell color on button this click
}

how can i create cell object in button action and change cell color? answer in objective-c also welcome.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
New iOS Dev
  • 1,937
  • 7
  • 33
  • 67
  • Various solutions here: https://stackoverflow.com/questions/28659845/swift-how-to-get-the-indexpath-row-when-a-button-in-a-cell-is-tapped and here: https://stackoverflow.com/questions/29913066/how-to-access-the-content-of-a-custom-cell-in-swift-using-button-tag and here: https://stackoverflow.com/questions/39585638/get-indexpath-of-uitableviewcell-on-click-of-button-from-cell. – Martin R Sep 21 '17 at 17:43

2 Answers2

0

You could create a custom object for your button where you would have an attribute to store the index of the cell where the button is.

These would be the steps:

  • Crear a custom objet for your button.
  • Add a var to store the IndexPath of your cell.
  • In func CellForRowAtIndexPath set the index path of each cell to its button.
  • When button is tapped check for the index path inside it and get the cell using your table view and this index.
  • Change the color of your cell

That would do the job.

Gabriel Goncalves
  • 5,132
  • 3
  • 25
  • 34
0

This answer is in swift 2.2.I have done this and is working fine for me,I think this should work for you:

func buttonClicked(sender:UIButton) {
    {
        let indexPath = NSIndexPath(forRow: sender.tag, inSection: 0)
        let cell = self.tableView.cellForRowAtIndexPath(indexPath)
        cell?.backgroundColor = UIColor.redColor()
    }
Niroj
  • 1,114
  • 6
  • 29