Search code examples
iosswiftbuttonaction

Changing button action on runtime pushing view controller weirdly


My code is so complex so Im gonna minimalize it a little bit.

I have a tableviewController that has 2 cell and a button in view.(Button not in cell). I'm changing button action according to selected cell :

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

This is my action buttons :

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

When page load, If I select a row and then tap button , Its perfecly worked.But , For example, If I select 1.row then change to selected row to 2.row and tap button , View pushes First row's viewcontroller (showAVC) and then pushes Second row's viewcontroller (showBVC) quickly.

How can I fix it?


Solution

  • Target keeps on adding-up as you keep selecting the rows you need to remove the previous target when you add a new one:

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