Passing variables from one view to an other

前端 未结 2 836
面向向阳花
面向向阳花 2021-01-17 02:09

I know this question as been asked over and over but it\'s still quite obscure to me, so I guess making an example with my code instead will probably be easier .

I k

相关标签:
2条回答
  • 2021-01-17 02:18

    By creating a @property called evTe or whatever in both view controllers.

    If the FirstViewController is responsible for creating the SecondViewController you could store the value of evTe in a property in FirstViewController and then after you have created the SecondViewController you set the evTe property there as well.

    - (IBAction) makeKeyboardGoAway;
    {
        [Te resignFirstResponder];  
        self.evTe = [Te.text integerValue];
    }
    

    // other method where SecondViewController is created

    SecondViewController* second = [[SecondViewController alloc] init];
    second.evTe = self.evTe;
    // do what ever
    

    --Edit--

    @interface FirstViewController : UIViewController {
    
        IBOutlet UITextField *Te;
        NSInteger evTe;
    
    }
    
    @property (nonatomic, retain) UITextField *Te;
    @property (nonatomic) NSInteger evTe;
    
    0 讨论(0)
  • 2021-01-17 02:31

    Have a look at NSNotification. You should send a notification that the particular value has changed and register for that notification in the second view controller.

    - (IBAction) makeKeyboardGoAway;
    {
        [Te resignFirstResponder];  
        evTe = [Te.text intValue];
    
        NSDictionary *changedValues = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:evTe] forKey:@"evTe"];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"evTeChanged" object:self userInfo:changedValues];
    
    }
    

    And in the viewDidLoad method of the other controller do:

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(methodToCall:) name:@"evTeChanged" object:nil];
    

    Now every time the first controller calls makeKeyboardGoAway the method - (void)methodToCall:(NSNotification *)aNotification will be called.

    Implement this method and ask the aNotification for its userInfo which is the NSDictionary you created in the first controller before posting the notification. Get the evTe value out of it and do whatever you want to do with that value.

    0 讨论(0)
提交回复
热议问题