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

时间:2018-12-14 21:54:05

标签: ios swift uitableview delegates protocols

我创建了一个自定义委托方法来更改表视图单元格的标签文本,但是看来该方法被调用了两次。添加断点后,它似乎会正确更改包含新标签文本的变量,但是随后再次调用它,这次变量为nil。正是第二次调用更改了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
    }
}

关于为什么两次调用该代表以及如何只调用一次的任何想法。或者,如果您有更好的建议从另一个ViewController更改tableview单元格标签,我欢迎您提出建议。

1 个答案:

答案 0 :(得分:-1)

您需要同时摆脱两者

let vitalVC = VitalsViewController()

 self.delegate = vitalVC

然后,当您实例化手动vc

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