首页 文章

从子视图中调用Root ViewController上的函数

提问于
浏览
2

我有一个名为“ViewController”的UIViewController类,它可以访问几个SKScenes .

我有这两个功能来展示和隐藏广告:

-(void)showBannerView{
    if (_adBanner && !_adBannerViewIsVisible){
        _adBannerViewIsVisible = true;

        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.5];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];

        CGRect frame = _adBanner.frame;
        frame.origin.x = 0.0f;
        frame.origin.y = 0.0f;

        _adBanner.frame = frame;

        [UIView commitAnimations];
    }
}

-(void)hideBannerView{
    if (_adBanner && _adBannerViewIsVisible){
        _adBannerViewIsVisible = false;

        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.5];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];

        CGRect frame = _adBanner.frame;
        frame.origin.x = 0.0f;
        frame.origin.y = -_adBanner.frame.size.height ;

        _adBanner.frame = frame;

        [UIView commitAnimations];
    }

}

我需要弄清楚的唯一剩下的事情是如何在正确的父ViewController上调用这些函数 .

如何在我的SKScenes中进行此操作?

我试过(从skscene内部):

[self.view.window.rootViewController hideBannerView];
[self.view.window.rootViewController showBannerView];

ViewController *parent = [[ViewController alloc] init];
[parent hideBannerView];

第一个只是抛出一个错误,而父代码没有做任何事情,因为它创建了另一个视图控制器而不是访问给定的视图控制器 .

我也尝试在'ViewController *'类型的skscene上创建一个属性,它不允许我从viewcontroller访问该属性(我试图将属性设置为'self',从skscene有效地引用viewcontroller)

1 回答

  • 3

    我对spriteKit并不完全熟悉,但我认为这应该是一样的 .

    在ViewDidLoad的RootViewController.h中添加:

    // Note Notification name:  you should probably use a constant
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(updateBannerView:)
                                                 name:@"kNotificationUpdateBannerView"
                                               object:nil];
    

    然后,仍然在RootViewController.h中添加:

    - (void) updateBannerView:(NSNotification *)note {
        NSDictionary * info = note.userInfo;
        BOOL shouldHide = [info[@"shouldHide"]boolValue];
    
        if (shouldHide) {
            NSLog(@"shouldHide");
            [self hideBannerView];
        }
        else {
            NSLog(@"shouldShow");
            [self showBannerView];
        }
    }
    

    现在,你们都已经成立了 . 无论何时想要调用它,请使用:

    BOOL shouldHide = YES; // whether or not to hide
    
    // Update Here!
    NSDictionary * dict = [[NSDictionary alloc]initWithObjectsAndKeys:[NSNumber numberWithBool:shouldHide], @"shouldHide", nil];
    
    [[NSNotificationCenter defaultCenter]postNotificationName:@"kNotificationUpdateBannerView" // Better as constant!
                                                       object:self 
                                                     userInfo:dict];
    

    现在,无论您在应用中的哪个位置,都可以隐藏/展示 Banner 广告!

相关问题