代码之家  ›  专栏  ›  技术社区  ›  SwiftyJD

尝试从单独的ViewController更改TableView单元格标签时调用了两次自定义委托方法

  •  0
  • SwiftyJD  · 技术社区  · 7 年前

    我创建了一个自定义委托方法来更改TableView单元格的标签文本,但该方法似乎被调用了两次。添加断点后,它会正确地更改包含新标签文本的变量,但随后再次调用它,这次变量为零。这是第二次调用,它正在更改label.text,但它是nil。设置方式如下:

        protocol ChangeInfoViewControllerDelegate {
            func changeInfoValue(vital: String)
        }
    
        //this class is where the new text value being created
        class ManualVitalsInputViewController: UIViewController {
          let vitalVC = VitalsViewController()
          var delegate: ChangeInfoViewControllerDelegate!
    
          override func viewDidLoad() {
                super.viewDidLoad()
    
                self.delegate = vitalVC
               } 
    
          @IBAction func saveButtonTapped(_ sender: Any) {
         delegate.changeVitalValue(vital: "Test") //This gets called twice, 2nd time is nil
                 dismiss(animated: true)
            }
        }
    
    //this is the controller where the text is being changed
    class VitalsViewController: UIViewController {
    
      func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    
    
            let vital = vitals[indexPath.row]
            cell.imageView.image = vital.image
    
            if changedManualVital != nil {
                cell.vitalTitleLabel.text = changedManualVital//where text should change to new text from delegate
            } else {
    
            cell.vitalTitleLabel.text = vital.title
            }
    
            return cell
        }
    }
    
    
    }
    
    //where delegate used
    extension VitalsViewController: ChangeInfoViewControllerDelegate {
        func changeVitalValue(vital:String){
            self.changedManualVital = vital
        }
    }
    

    关于为什么调用委托两次以及如何只调用一次的任何想法。或者,如果您有更好的建议,可以从另一个视图控制器更改TableView单元格标签,我愿意接受建议。

    1 回复  |  直到 7 年前
        1
  •  -1
  •   Shehata Gamal    7 年前

    你得把这两个都除掉

    let vitalVC = VitalsViewController()
    

     self.delegate = vitalVC
    

    然后当您实例化手动VC时

     let vc = self.storyboard............... as! ManualVitalsInputViewController
     vc.delegate = self /// here is the actual link
     // present/push