简体   繁体   中英

How can I know which indexPath.row my button in when I press a button to push to another ViewController?

Maybe the question is not clearly enough.

I mean I have a TableView,and it has a Prototype Cell and this Cell has a button.

I set a segue name "ForMore" which is combine 2 ViewControllers

But I reuse this Cell many times.

And this is result:

When I click everyone of the button in all cells.It will jump to another ViewController.

But I need to know which button I have clicked because that ViewController need initialize according to which cell I clicked.

So, how can I know which cell I clicked when I reuse a cell many times.

The best way of doing anything with custom cells is to have a custom class to go along with it.

That way the button is a property of the class and the action can be sent to the cell instead.

That way you can use a block to customise what the button does at the point of creating it.

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    // create the cell...

    cell.buttonBlock = {
        self.buttonTappedAtIndexPath(indexPath)
    }

    return cell
}

Or something like this.

I also had this problem once, and I did this way.

// CustomCellClass

var tableViewdelegate: MyTableViewDelegateClass?

// button in cell action
@IBAction func buttonPressed(sender: AnyObject) {
    tableViewdelegate?.buttonPressedInCell(cell: self)
}

// MyTableViewDelegateClass

func buttonPressedInCell(cell: CustomCellClass) {
    let indexPath = tableView.indexPathForCell(cell)

    // other logic you have
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    var cell =  // create your cell or deque

    cell.tableViewdelegate = self

    return cell
}

I have tried all of the method above but didn't work.Maybe I can't understand the answers well.

But I fixed this problem by my self.

This is what I did:

1、Create a new class inherit UIButton named 'ForMore' and declare a var named 'row'

2、Combine the ForMoreButton to the custom cell with a name 'ForMoreButton'

3、Assign the indexPath.row to cell.ForMoreButton.row when I create the cell in the method

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell

4、In the ViewController my tableview inside, combine the ForMoreButton to this ViewController directly with an action 'ButtonTapped' and then we can get the row from (sender as! ForMore).row

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM