繁体   English   中英

当我按下按钮推送到另一个ViewController时,如何知道哪个indexPath.row我的按钮?

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

也许问题不够清楚。

我的意思是我有一个TableView,它有一个Prototype Cell,这个Cell有一个按钮。

我设置了一个名为“ForMore”的segue名称,它组合了2个ViewControllers

但我多次重复使用这个Cell。

这是结果:

当我单击所有单元格中的每个按钮时,它将跳转到另一个ViewController。

但我需要知道我点击了哪个按钮,因为ViewController需要根据我点击的单元格进行初始化。

那么,当我多次重复使用单元格时,如何知道我单击了哪个单元格。

使用自定义单元格执行任何操作的最佳方法是使用自定义类。

这样,按钮是类的属性,操作可以发送到单元格。

这样,您可以使用块来自定义按钮在创建时所执行的操作。

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

    // create the cell...

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

    return cell
}

或类似的东西。

我曾经遇到过这个问题,我这样做了。

// 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
}

我已经尝试了上述所有方法,但没有奏效。也许我无法理解答案。

但我自己解决了这个问题。

这就是我做的:

1,创建一个新类继承名为'ForMore'的UIButton并声明一个名为'row'的var

2,将ForMoreButton与名为'ForMoreButton'的自定义单元格相结合

3,当我在方法中创建单元格时,将indexPath.row分配给cell.ForMoreButton.row

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

4,在ViewController中我的tableview里面,直接将ForMoreButton与这个ViewController结合使用'ButtonTapped'动作,然后我们可以从(发送者为!ForMore).row获取行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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