提问者:小点点

在运行时改变按钮操作,奇怪地推视图控制器


我的代码太复杂了,所以我要把它最小化一点。

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

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是我的按钮插座

这是我的操作按钮:

 @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)
}

当页面加载时,如果我选择一个行,然后点击按钮,它的工作很完美。但是,例如,如果我选择1.行,然后将选择的行更改为2.行和点击按钮,视图会快速地按下第一行的viewcontroller(showAVC),然后按下第二行的viewcontroller(showBVC)。

我该怎么修好呢?


共2个答案

匿名用户

当您不断选择需要在添加新目标时移除上一个目标的行时,目标将继续累加:

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