Search This Blog

Thursday, 27 March 2014

SIMPLE PROTOCOL & DELEGATE EXAMPLE

PROTOCOL & DELEGATE
two controllers

FirstViewController
SecondViewController

SecondViewController.h
@protocol SecondViewControllerDelegate;
@property (nonatomic, weak) id<SecondViewControllerDelegate> delegate;

@protocol SecondViewControllerDelegate <NSObject>

- (void)SecondViewController:(SecondViewController*)viewController
             didChooseValue:(CGFloat)value;

SecondViewController.m
-(IBAction)SecondTap:(id)sender
{
    id<SecondViewControllerDelegate> strongDelegate = self.delegate;
    
    // Our delegate method is optional, so we should
    // check that the delegate implements it
    
    if ([strongDelegate respondsToSelector:@selector(SecondViewController:didChooseValue:)]) {
        [strongDelegate SecondViewController:self didChooseValue:[sender tag]];
    }
}

FirstViewController.h

@interface FirstViewController : UIViewController<SecondViewControllerDelegate>

FirstViewController.m

-(IBAction)Add:(id)sender
{
    SecondViewController *objsecond =[[SecondViewController alloc]init];
    [objsecond setDelegate:self];
    [self.view addSubview:objsecond.view];

}

- (void)SecondViewController:(SecondViewController *)viewController didChooseValue:(CGFloat)value
{
    
    // Do something with value...
    
    // ...then dismiss the child view controller
    [viewController.view removeFromSuperview];

}

No comments:

Post a Comment