1

I am trying to access the previous viewcontroller in a navigation stack. I want to set a label's text property before I pop back to it. It crashes after the second line in the function. Thanks for any help.

func goBack(){
    let i = (navigationController?.viewControllers.count)! - 1
    let itemViewController = navigationController?.viewControllers[i] as     ItemViewController
    itemViewController.typeValueLbl.text = itemName
    navigationController?.popViewControllerAnimated(true)
}
Nick D
  • 23
  • 1
  • 6

2 Answers2

1

You are trying to set a property of your previous controller.

The ideal way of doing it would be using Protocols and Delegates.

Write a Protocol in your PUSHED class and declare a delegate property.

When your ItemViewController pushes this class, set the delegate to self.

Then you can call the delegate method, in goBack method, that sets your label text.

To learn Protocols and Delegates in Swift refer documentation

Mayur Deshmukh
  • 1,169
  • 10
  • 25
0

A quote from this thread

Here's the implementation of the accepted answer:

- (UIViewController *)backViewController {
NSInteger numberOfViewControllers = self.navigationController.viewControllers.count;

if (numberOfViewControllers < 2)
    return nil;
else
    return [self.navigationController.viewControllers objectAtIndex:numberOfViewControllers - 2]; }
Community
  • 1
  • 1
Schemetrical
  • 5,506
  • 2
  • 26
  • 43