Jesse Serre
Jesse Serre

Reputation: 11

Using storyboarding in xCode how can I change the value of a label from a different view?

I'm writing an app that uses storyboarding and I want to update the labels in one view by clicking a button in a previous view.

_label.text = variable1;

is the line I would use to change the value of label, which is in the next view, when I click the button. Using this method I can easily change labels in the same view as the button but it does nothing when I go to the next view and see empty labels.

I've tried looking everywhere and found similar issues but couldn't find anything that worked for me so any solution would be very appreciated!

Upvotes: 0

Views: 665

Answers (2)

Andriy Gordiychuk
Andriy Gordiychuk

Reputation: 6272

Unfortunately, it is not possible to connect IBOutlets between different scenes in storyboard.

It is difficult to suggest some precise solution because you have to provide more details about the setup which you have. Still, it is possible to outline some possible solutions:

Using prepareForSegue

If the view controller which you want to modify appears after the segue is performed you can customise its appearance in prepareForSegue function.

Using delegation

You can assign the view controller which wants to modify another view controller as its delegate. For example, if ViewController1 wants to modify ViewController2:

@interface ViewController1: UIViewController {}
    
@property (nonatomic,weak) ViewController2 *controllerThatIWantToModify;

with such setup you can call:

self.controllerThatIWantToModify.label.text = variable1;

Upvotes: 1

nameCensored
nameCensored

Reputation: 86

You use storyboards, so there must be a segue from your first viewController (with the button) to your second (with labels in it).

If it is the case, you can set up the labels of the second view controller from the prepareForSegue method of your first view controller.

This method is called with a segue object which has a destinationViewController property which is your second view controller.

If you have several segue from this viewController, you should check if it is the right segue and then set it up.

To do that you need to set up outlets that gives you access to the labels from the viewController.

Then you can either write a setUpLabelsWith:(NSString)text1 ... method in your view controller, or directly access the outlets from the first view controller (supposing their are not private).

Yes this supposes your second view controller has a custom class.

Upvotes: 0

Related Questions