Question

In my presenting view controller, I have the following prepareForSegue function

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if([[segue identifier] isEqualToString:@"goToView2"]){
        ViewController2 *controller2 = [segue destinationViewController];
        controller2.multiplierStepper.value = 7.0;
        controller2.randomString = @"string set from Scene 1";
    }
}

In ViewController2 there is an outlet for my UIStepper's value and an NSString

@property (strong, nonatomic) IBOutlet UIStepper *multiplierStepper;
@property (strong, nonatomic) NSString *randomString;

In ViewController2.m viewDidLoad, I am testing the values set above by the presenting view controller

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.        
    NSLog(@"in viewDidLoad: self.multiplierStepper.value: %f", self.multiplierStepper.value);
    NSLog(@"in viewDidLoad: randomstring: %@", self.randomString);
}

The console output works nicely for the NSString, but the UIStepper value always shows the initial value defined in the Interface Builder (1).

[10682:f803] in viewDidLoad: self.multiplierStepper.value: 1.000000
[10682:f803] in viewDidLoad: randomstring: string set from Scene 1

The answer is probably glaringly obvious, but I cannot figure out how to set the value of a stepper in my destination view controller from the presenting view controller.

Any ideas what I'm doing wrong?

Was it helpful?

Solution

Do not set directly the value of the UIStepper in the the prepareForSeque method , it will not work !

You have to declare a property that will contains the value and then set the value of the stepper in the viewDidLoad event of the second controller ...

First of all declare an additional property to your second view controller (ViewController2) header file :

@property (nonatomic) double stepperValue;

Then set the property value :

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if([[segue identifier] isEqualToString:@"goToView2"]){
        ViewController2 *controller2 = [segue destinationViewController];
        controller2.stepperValue = 7.0;
        controller2.randomString = @"string set from Scene 1";
    }
}

Then in the destination viewController (ViewController2) :

- (void)viewDidLoad
{
    multiplierStepper.value = [self stepperValue];
}

Note

Bear in mind that the best thing for encapsulation would be declaring the IBOutlet as private member of the class, to avoid that a client of the class can access directly the IBOutlet; to make an IBOutlet private you have to declare it in a class extension in the .m file ...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top