trying to update a UILabel on a parent view controller when dismissing the modal view

前端 未结 3 765
北海茫月
北海茫月 2020-12-06 21:53

I am trying to update a UILabel in a parent View after someone makes a change in a modal view. So, after they click \"save\" ... the newly entered value would change what t

3条回答
  •  余生分开走
    2020-12-06 22:28

    To elaborate on my comment. This is how I would implement a delegation method to update the label.

    In the header of the parent view controller:

    #import "ModalViewController.h"
    
    @interface ViewController : UIViewController 
    
    /* This presents the modal view controller */
    - (IBAction)buttonModalPressed:(id)sender;
    
    @end
    

    And in the implementation:

    /* Modal view controller did save */
    - (void)modalViewControllerDidSave:(ModalViewController *)viewController withText:(NSString *)text
    {
        NSLog(@"Update label: %@", text);
    }
    
    /* Prepare for segue */
    - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
    {
        if ([segue.identifier isEqualToString:@"modalSegue"])
        {
            ModalViewController *mvc = (ModalViewController *) segue.destinationViewController;
            mvc.delegate = self;
        }
    }
    
    /* Present modal view */
    - (IBAction)buttonModalPressed:(id)sender
    {
        [self performSegueWithIdentifier:@"modalSegue" sender:self];
    }
    

    Here you see the delegation method in the top.

    The header of the modal view controller would contain the delegation protocol like this:

    @protocol ModalViewControllerDelegate;
    
    @interface ModalViewController : UIViewController
    
    @property (nonatomic, weak) id  delegate;
    
    - (IBAction)buttonSavePressed:(id)sender;
    
    @end
    
    @protocol ModalViewControllerDelegate 
    - (void)modalViewControllerDidSave:(ModalViewController *)viewController withText:(NSString *)text;
    @end
    

    The implementation of the modal view controller would contain a method similar to this one:

    /* Save button was pressed */
    - (IBAction)buttonSavePressed:(id)sender
    {
        if ([self.delegate respondsToSelector:@selector(modalViewControllerDidSave:withText:)])
            [self.delegate modalViewControllerDidSave:self withText:@"Some text"];
    
        [self dismissModalViewControllerAnimated:YES];
    }
    

    When the save button is pressed, the delegate is notified and the text in your text view is sent through the delegation method.

提交回复
热议问题