iOS通过委托解除视图控制器

时间:2014-05-06 18:42:18

标签: ios delegates

我正试图通过委托解雇视图控制器,但它没有响应。

我的主页是顶视图控制器,当触摸屏幕的某个区域时,规则视图控制器被推到主页的顶部。我希望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

1 个答案:

答案 0 :(得分:2)

在touchesBegan方法中,您需要将Rules委托设置为self。

Rules *controller = (Rules *)[self.storyboard instantiateViewControllerWithIdentifier:@"Rules"];
controller.delegate = self;
[self presentViewController:controller animated:YES completion:nil];