swift ios 按下按钮时触发 table 索引

swift ios trigger a table index when button is pressed

我的 table 中有一个按钮,单击它时会触发选定的 table 索引。例如,当我单击选定索引处的按钮时,它将触发下面的代码。谢谢

代码

func indexWasPressed(cell: ToDoListTableViewCell) {
 trigger it here
}


func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            print("You selected cell #\(indexPath.item)!")

使用下面的代码从 TableViewCell 获取索引:

func indexWasPressed(cell: ToDoListTableViewCell) {
    let indexPath = yourTableView.indexPath(for: cell)
    let index = indexPath.row
} 

试试这个:-

 @objc func buttonPressed(sender: UIButton) {
    // printing selected row
  print("index path: \(sender.tag)")

    //do you want section try this
   var section = Int()

    let pointInTable: CGPoint = sender.convert(sender.bounds.origin, to: self.tblView)
    let cellIndexPath = self.tblView.indexPathForRow(at: pointInTable)
    section(cellIndexPath!)
    section = cellIndexPath!.row
    print(section)


}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    print("cell for rows in \(indexPath.section)")


        let cell = tableView.dequeueReusableCell(withIdentifier: "cellIdentifire", for: indexPath) as! yourcell

        cell.yourbutton.tag = indexpath.row

        cell.yourbutton.addTarget(self, action: #selector(buttonpressed(sender:)), for: UIControlEvents.touchUpInside)
        }