通过Button Swift中的标签发送行和部分

Gre*_*ory 5 button uitableview ios sender-id swift

我在cellForRowAtIndexPath中有这个

   cell.plusBut.tag = indexPath.row
   cell.plusBut.addTarget(self, action: "plusHit:", forControlEvents: UIControlEvents.TouchUpInside)
Run Code Online (Sandbox Code Playgroud)

而这个功能在外面:

func plusHit(sender: UIButton!){
    buildings[sender.tag].something = somethingElse
}
Run Code Online (Sandbox Code Playgroud)

是否有可能发送indexPath.row 和 indexPath.section,或某些替代?

谢谢!

编辑

我这样接近它:

我的自定义按钮

class MyButton: UIButton{

    var myRow: Int = 0
    var mySection: Int = 0

}
Run Code Online (Sandbox Code Playgroud)

我的自定义细胞

class NewsCell: UITableViewCell{

    @IBOutlet weak var greenLike: MyButton!
Run Code Online (Sandbox Code Playgroud)

在CellForRowAtIndexPath中

    cell.greenLike.myRow = indexPath.row
Run Code Online (Sandbox Code Playgroud)

我在这一行上收到错误.

Cal*_*leb 13

是否可以发送indexPath.row和indexPath.section,或者一些替代?

如果对部分中可能的行数施加限制,则可以将两者合并为一个数字.例如,如果您愿意说某个部分中的行总是少于1000行,您可以使用:

cell.plusBut.tag = (indexPath.section * 1000) + indexPath.row
Run Code Online (Sandbox Code Playgroud)

然后使用mod和division运算符来恢复:

row = sender.tag % 1000
section = sender.tag / 1000
Run Code Online (Sandbox Code Playgroud)

另一种可能性是检查按钮的超视图(以及它的超视图等),直到找到单元格.获得单元格后,可以从表中获取该单元格的索引路径.

第三个选项,也许是最好的选项,是让按钮以单元格而不是其他对象为目标.然后,单元可以使用自身作为发送方在视图控制器或其他对象中触发操作.


Ind*_*ore 4

您可以创建 的子类UIButton并在其中创建额外的属性部分。然后您可以将该类用于单元格按钮。您可以对行执行相同的操作。

子类化后有以下几种可能的方法UIButton

cell.plusBut.tag = indexPath.row
cell.plusBut.section = indexPath.section
Run Code Online (Sandbox Code Playgroud)

或者

cell.plusBut.row = indexPath.row
cell.plusBut.section = indexPath.section
Run Code Online (Sandbox Code Playgroud)

或者

cell.plusBut.indexPath = indexPath
Run Code Online (Sandbox Code Playgroud)

选择适合你的。