Passing values from second view to firstView in Xcode

前端 未结 1 1151
野性不改
野性不改 2020-12-22 08:10

I have been stuck here.

I have a NSString in Appdelegate. And I have two views called firstview,second view.In first view I have a label and set text from stringvari

相关标签:
1条回答
  • 2020-12-22 08:42

    There is a pattern how to do such things. You should define a protocol like this:

    @protocol FirstViewDelegate <NSObject>
    
    - (void)didDismissSecondView;
    
    @end
    

    Your first view should conform to this protocol:

    @interface FirstView: UIViewController <FirstViewDelegate> {
    ...
    

    in its implementation add function didDismissSecondView:

    - (void) didDismissSecondView
    {
        AppDelegate *del = [[UIApplication sharedApplication] delegate];
    
        [btn setTitle:del.str1];
    }
    

    Your second view has to have a property

    @interface SecondView : UIViewController
    {
         id<FirstViewDeledate> delegate;
    }
    @property (nonatomic, retain) id<FirstViewDeledate> delegate;
    

    When you show your second view from the first view set its delegate to self of first view in your function:

    -(IBAction)gotoView2:(id)sender
    {
        SecondView *aView = [[SecondView alloc] init] // or whatever
        ...//other initialization code
        aView.delegate = self;
        ... // show it
    
    }
    

    and before you dismiss the second view:

    -(IBAction)gotoView1:(id)sender
    {
    
        AppDelegate *del = [[UIApplication sharedApplication] delegate];
        [del setStr1:@"Home"];
    
        [self.delegate didDismissSecondView];
    
        [self.view removeFromSuperView];
    }
    

    And you done. A bit long, but works.

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