我正在使用tableviewcell,在该单元格中,我正在使用两个UIButtons,即btnView和btnEdit。当我点击btnEdit时,我想获取此按钮单元格的indexPath。我如何得到 ?
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "DepartmentCell", for: indexPath) as! ShowDepttTVCell
//Set action to buttons
cell.btnView.addTarget(self, action: #selector(btnView), for: .touchUpInside)
cell.btnEdit.addTarget(self, action: #selector(btnEdit), for: .touchUpInside)
return cell
}
@objc func btnView()
{
let viewDepttVC = self.storyboard?.instantiateViewController(withIdentifier: "Detailed Department") as! DetailedDepttVC
self.navigationController?.pushViewController(viewDepttVC, animated: true)
}
@objc func btnEdit()
{
//I want to get the indexpath of this cell button.
print("Selected iNdex : (r)")
print("Edit")
let editDeptt = self.storyboard?.instantiateViewController(withIdentifier: "Add Department") as! AddDepartmentVC
editDeptt.btnTag = 0
//editDeptt.strDName =
self.navigationController?.pushViewController(editDeptt, animated: true)
}
检查以下代码:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "DepartmentCell", for: indexPath) as! ShowDepttTVCell
cell.btnView.tag = indexPath.row
cell.btnEdit.tag = indexPath.row
//Set action to buttons
cell.btnView.addTarget(self, action: #selector(btnView(sender:)), for: .touchUpInside)
cell.btnEdit.addTarget(self, action: #selector(btnEdit(sender:)), for: .touchUpInside)
return cell
}
@objc func btnView(sender: UIButton)
{
let index = sender.tag
let indexPath = IndexPath(row: index, section: 0)
let viewDepttVC = self.storyboard?.instantiateViewController(withIdentifier: "Detailed Department") as! DetailedDepttVC
self.navigationController?.pushViewController(viewDepttVC, animated: true)
}
@objc func btnEdit(sender: UIButton)
{
let index = sender.tag
let indexPath = IndexPath(row: index, section: 0)
//I want to get the indexpath of this cell button.
print("Selected iNdex : (r)")
print("Edit")
let editDeptt = self.storyboard?.instantiateViewController(withIdentifier: "Add Department") as! AddDepartmentVC
editDeptt.btnTag = 0
//editDeptt.strDName =
self.navigationController?.pushViewController(editDeptt, animated: true)
}
两种方式
第一。 cell.btnView.tag = indexPath.row
将@objc func btnView()
更改为@objc func btnView(btn: UIButton)
所以你可以使用btn.tag
第二,这是一种了解单元格使用UIResponder的方法我的博客