Passing data back from a modal view in WatchKit

前端 未结 6 1698
耶瑟儿~
耶瑟儿~ 2020-12-03 09:41

When modally presenting, or pushing, an interface controller we can specify the context parameter to pass some data to the new controller as follows.

         


        
6条回答
  •  独厮守ぢ
    2020-12-03 10:13

    You can transfer back information via Protocols by passing self within the context:

    InterfaceController.m

    // don't forget to conform to the protocol!
    @interface InterfaceController() 
    
    //...
    
    // in some method
    [self pushControllerWithName:@"PictureSelectionController" 
                         context:@{@"delegate" : self}];
    

    And setting the delegate like so:

    PictureSelectionController.m

    @property (nonatomic, unsafe_unretained) id delegate;
    
    // ...
    
    - (void)awakeWithContext:(id)context {
        [super awakeWithContext:context];
    
        // Configure interface objects here.
        if ([context isKindOfClass:[NSDictionary class]]) {
            self.delegate = [context objectForKey:@"delegate"];
        }
    }
    

    Don't forget to declare your protocol:

    PictureSelectionController.h

    @protocol PictureSelectionControllerDelegate 
    
    - (void)selectedPicture:(UIImage *)picture;
    
    @end
    

    Then you can call that method from PictureSelectionController.m:

    - (IBAction)buttonTapped {
        // get image
        UIImage *someCrazyKatPicture = //...
        [self.delegate seletedPicture:someCrazyKatPicture];
    }
    

    And receive it in the delegate method within InterfaceController.m:

    - (void)selectedPicture:(UIImage *)picture {
        NSLog(@"Got me a cat picture! %@", picture);
    }
    

提交回复
热议问题