在运行时更改按钮动作奇怪地推送视图控制器

Changing button action on runtime pushing view controller weirdly

我的代码太复杂了,所以我要尽量简化它。

我有一个 tableviewController,它在视图中有 2 个单元格和一个按钮。(按钮不在单元格中)。 我正在根据 selected 单元格更改按钮操作:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  if indexPath.row == 0{
    self.botButton.addTarget(self, action: #selector(self.showA), for: .touchUpInside)
  else{
    self.botButton.addTarget(self, action: #selector(self.showB), for: .touchUpInside)

  } 

botButton is my button outlet

这是我的操作按钮:

 @objc func showA(){
       let showParcelsViewController = self.storyboard?.instantiateViewController(withIdentifier: "showA") as! showAVC
       self.navigationController?.pushViewController(showParcelsViewController, animated: true)
   }



@objc func showB(){
    let decribeland = self.storyboard?.instantiateViewController(withIdentifier: "showB") as! showBVC
              self.navigationController?.pushViewController(decribeland, animated: true)
}

当页面加载时,如果我 select 一行然后点击按钮,它完美 worked.But ,例如,如果我 select 1.row 然后更改为 selected row to 2.row 然后点击按钮,View pushes First row's viewcontroller (showAVC) 然后快速推送第二行的 viewcontroller (showBVC)。

我该如何解决?

随着您不断选择需要删除的行,目标不断增加,当您添加新目标时:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if indexPath.row == 0 {
        botButton.removeTarget(self, action: #selector(self.showB), for: .touchUpInside)
        botButton.addTarget(self, action: #selector(self.showA), for: .touchUpInside)
    } else {
        botButton.removeTarget(self, action: #selector(self.showA), for: .touchUpInside)
        botButton.addTarget(self, action: #selector(self.showB), for: .touchUpInside)
    }
}

这是另一种方法。

didSelectRowAt

中将按钮tag设置为indexPath.row
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) 
{
   self.botButton.tag = indexPath.row
} 

然后使用按钮 tag 知道要显示哪个控制器。

@IBAction func showBtnPressed(sender : UIButton) { // 
    let index = sender.tag
    if index == 0 {
        let showParcelsViewController = self.storyboard?.instantiateViewController(withIdentifier: "showA") as! showAVC
        self.navigationController?.pushViewController(showParcelsViewController, animated: true)
    } else {
        let decribeland = self.storyboard?.instantiateViewController(withIdentifier: "showB") as! showBVC
        self.navigationController?.pushViewController(decribeland, animated: true)
    }
}