indexpath row after a press button in a table view cell

Dear all I have this problem:

I have a table view with some row, in every row there is a button, a when it is submitted, I have to make some update (php) via json.

My problem is that I'm not able to get the indexpath row to clean the table after the php update.

Does anyone encountered the same problem and can help me?


Thanks in advance,


Angelo.

Answered by goldsdad in 194376022

Here's an alternative to storing the row number in a tag:


@IBAction func submit(_ sender: UIButton) {
    var superview = sender.superview
    while let view = superview, !(view is UITableViewCell) {
        superview = view.superview
    }
    guard let cell = superview as? UITableViewCell else {
        print("button is not contained in a table view cell")
        return
    }
    guard let indexPath = tableView.indexPath(for: cell) else {
        print("failed to get index path for cell containing button")
        return
    }
    // We've got the index path for the cell that contains the button, now do something with it.
    print("button is in row \(indexPath.row)")
}

When you create the buttons, you can set a "tag" that is an integer. You can then look at that tag when you get the button press. One way to use this is to directly store the row number in the tag, but only do that if you know that there are no other buttons that can be pressed. Otherwise, you can create a new tag number when you create each button, and then have a dictionary where you store the mapping between the tag and the data that you want.

Accepted Answer

Here's an alternative to storing the row number in a tag:


@IBAction func submit(_ sender: UIButton) {
    var superview = sender.superview
    while let view = superview, !(view is UITableViewCell) {
        superview = view.superview
    }
    guard let cell = superview as? UITableViewCell else {
        print("button is not contained in a table view cell")
        return
    }
    guard let indexPath = tableView.indexPath(for: cell) else {
        print("failed to get index path for cell containing button")
        return
    }
    // We've got the index path for the cell that contains the button, now do something with it.
    print("button is in row \(indexPath.row)")
}

Thanks a lot ahltorp for the answer, I did it like you say, but when I try to assign it to the indexpath.row it gave me an error, "you can't use a integer value to a NSIndexPath.

Thanks a lot goldsdad it's perfect for me!

have a nice day!

You're welcome!

Yes, you have to create an NSIndexPath from it like this: NSIndexPath(index: index)

indexpath row after a press button in a table view cell
 
 
Q