I created a custom delegate method to change the label text of a tableview cell but it appears the method is being called twice. After adding breakpoints it appears it's changing the variable that contains the new label text correctly, but then it calls it a second time, this time the variable is nil. It's this second call that is changing the label.text but its nil. this is how it's setup:
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
}
}
Any idea on why the delegate is called twice and how to only call once. Or if you have better suggestion to change a tableview cell label from another viewcontroller I'm open to suggestions.
You need to get rid of both
let vitalVC = VitalsViewController()
and
self.delegate = vitalVC
Then when you instantiate the manual vc
let vc = self.storyboard............... as! ManualVitalsInputViewController
vc.delegate = self /// here is the actual link
// present/push