Domanda

I'm trying to dismiss a view controller through a delegate, but it's not responding.

My HomePage is the top view controller, and when a certain area of the screen is touched, the Rules view controller is pushed on top of the HomePage. I want the HomePage view controller to dismiss the Rules view controller through the delegate

//HomePage

@interface HomePage : UIViewController <RulesControllerDelegate>
@end

//HomePage.m

#import "HomePage.h"
@implementation HomePage 

- (void)viewDidLoad{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.   
}


-(void)touchesBegan:(NSSet *) touches withEvent:(UIEvent *)event{
    int offset = 30;
    UITouch *theTouch = [touches anyObject];
    CGPoint location = [theTouch locationInView:self.view];

    if (location.x > gameLabel.frame.origin.x - offset && location.y < gameLabel.center.y + offset && location.y > gameLabel.center.y - offset) {
        NSLog(@"touched game");
    }

    if (location.x < rulesLabel.frame.origin.x + rulesLabel.frame.size.width + offset && location.y < rulesLabel.center.y + offset && location.y > rulesLabel.center.y - offset) {
        NSLog(@"touched rules");

        UIViewController *controller = [self.storyboard instantiateViewControllerWithIdentifier:@"Rules"];
        [self presentViewController:controller animated:YES completion:nil];
    }
}

#pragma mark - RulesControllerDelegate

- (void)rulesControllerDidCancel:(Rules *)controller{

    [self dismissViewControllerAnimated:YES completion:nil];
}

@end

//Rules.h

@class Rules;
@protocol RulesControllerDelegate <NSObject>
- (void)rulesControllerDidCancel:(Rules *)controller;
@end

@interface Rules : UIViewController

@property (nonatomic, weak) id <RulesControllerDelegate> delegate;

- (IBAction)cancel:(id)sender;

@end

//Rules.m

#import "Rules.h"

@implementation Rules
@synthesize delegate;

- (IBAction)cancel:(id)sender {
    [delegate rulesControllerDidCancel:self];  //why isn't this called//////////////////////
    //[self dismissViewControllerAnimated:YES completion:nil];
}

@end
È stato utile?

Soluzione

In your touchesBegan method you need to set the Rules delegate to self.

Rules *controller = (Rules *)[self.storyboard instantiateViewControllerWithIdentifier:@"Rules"];
controller.delegate = self;
[self presentViewController:controller animated:YES completion:nil];
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top