【问题标题】:How can I know which indexPath.row my button in when I press a button to push to another ViewController?当我按下按钮推送到另一个 ViewController 时,如何知道我的按钮在哪个 indexPath.row 中?
【发布时间】:2015-07-27 08:37:25
【问题描述】:

也许问题不够清楚。

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

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

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

这是结果:

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

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

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

【问题讨论】:

标签: ios swift


【解决方案1】:

使用自定义单元格做任何事情的最佳方式是拥有一个自定义类来配合它。

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

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

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

    // create the cell...

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

    return cell
}

或者类似的东西。

【讨论】:

【解决方案2】:

我曾经也遇到过这个问题,我就是这样做的。

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

【讨论】:

  • 使用块/闭包的可行替代方法是使用这样的委托/协议方法。
【解决方案3】:

上面的方法我都试过了,还是不行。可能是我没听懂答案。

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

这就是我所做的:

1、新建一个类继承UIButton名为‘ForMore’并声明一个var名为‘row’

2、将 ForMoreButton 与名为“ForMoreButton”的自定义单元格组合起来

3、我在方法中创建单元格时将indexPath.row赋值给cell.ForMoreButton.row

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

4、在我的tableview里面的ViewController中,直接把ForMoreButton和这个ViewController结合一个action‘ButtonTapped’就可以从(sender as!ForMore).row中获取行了

【讨论】:

  • 我也无法理解,您介意解释一下吗?我需要它。
猜你喜欢
  • 2020-09-24
  • 1970-01-01
  • 2021-05-17
  • 1970-01-01
  • 2022-08-18
  • 2023-01-20
  • 2021-10-08
  • 1970-01-01
相关资源
最近更新 更多