从viewWillLayoutSubviews移动到viewDidLoad后,视图未显示

时间:2014-01-04 19:46:53

标签: ios objective-c ios7 sprite-kit

我一直在努力教自己Objective-C,但我在查看方面遇到了一些麻烦。

将所有内容从viewWillLayoutSubviews移动到viewDidLoad后,我的场景无法呈现。 MyScene.m中的代码正常工作,我无法看到它。我在这里缺少一些明显的缺陷吗?

上面提供了以前的viewWillLayoutSubviews方法。此处的所有内容都被直接切换为viewDidLoad,不包括[super viewDidLayoutSubviews]

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];

    SKView * skView = (SKView *)self.view;
    if (!skView.scene) 
    {
        skView.showsFPS = YES;
        skView.showsNodeCount = YES;

        SKScene * scene = [MyScene sceneWithSize:skView.bounds.size];
        scene = [MyScene sceneWithSize:skView.bounds.size];
        scene.scaleMode = SKSceneScaleModeAspectFill;

        [skView presentScene:scene];
    }

    UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc] initWithTarget:(scene) action:@selector(screenSwipedRight)];
    swipeRight.numberOfTouchesRequired = 1;
    swipeRight.direction=UISwipeGestureRecognizerDirectionRight;
    [self.view addGestureRecognizer:(swipeRight)];

    UISwipeGestureRecognizer *swipeLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:(scene) action:@selector(screenSwipedLeft)];
    swipeLeft.numberOfTouchesRequired = 1;
    swipeLeft.direction=UISwipeGestureRecognizerDirectionLeft;
    [self.view addGestureRecognizer:(swipeLeft)];

    UISwipeGestureRecognizer *swipeUp = [[UISwipeGestureRecognizer alloc] initWithTarget:(scene) action:@selector(screenSwipedUp)];
    swipeUp.numberOfTouchesRequired = 1;
    swipeUp.direction=UISwipeGestureRecognizerDirectionUp;
    [self.view addGestureRecognizer:(swipeUp)];

}

如果有帮助,我会将所有内容从viewWillLayoutSubviews移到viewDidLoad,以避免每次视图旋转时重新创建手势识别器。

感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

你为什么这样做?初始化SKScene的可接受方式是viewWillLayoutSubviews

只需在!skView.scene块内创建手势识别器:

if (!skView.scene) 
{
    // init everything here that should be initialized only once
    // AND should not re-run every time the view rotates
}

就这么简单。

答案 1 :(得分:1)

我想,你错过了如下初始化你的skView

SKView * skView = (SKView *)self.view;

在访问其场景属性之前。