我可以从视图控制器外部引用子视图吗?

时间:2013-12-15 20:31:03

标签: ios iphone objective-c ios7 uigesturerecognizer

我试图在我的“MyScene.m”文件中使用手势识别器在屏幕左半部分出现手势时移动精灵。为此,我在视图控制器中添加了一个子视图,其中框架与屏幕左侧相匹配,并在MyScene中添加了手势识别器。手势识别器在MyScene中,因为它调用MyScene中使用同一文件中的精灵的方法。

问题是我的新子视图“leftView”无法从Myscene引用。有没有办法让新的子视图可用于不同的实现文件?

我已提供相关代码供以下参考。我是新手(把它当作一种爱好),并感谢你能给予的任何帮助。如果你知道一个更好的方法来实现我想要的结果我很乐意听取你的建议。谢谢!

ViewController.m:

@implementation ViewController

- (void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];

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


      // Create and configure the scene.
      SKScene * scene = [MyScene sceneWithSize:skView.bounds.size];
      scene.scaleMode = SKSceneScaleModeAspectFill;
      //skView.scene.physicsWorld.gravity = CGVectorMake(0, skView.scene.physicsWorld.gravity.dy*-1);
      // Present the scene.
      [skView presentScene:scene];

        UIView *leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width/2, self.view.bounds.size.height)];
        [leftView setBackgroundColor:[UIColor redColor]];
        [leftView setAlpha:0.2];
        [self.view addSubview:leftView];
    }
}

MyScene.m:

@implementation MyScene

-(id)initWithSize:(CGSize)size {    
    if (self = [super initWithSize:size]) 
        self.backgroundColor = [SKColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0];
    }
    return self;
}


-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [super touchesBegan:touches withEvent:event];
    UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc] initWithTarget:(self) action:@selector(screenSwipedRight)];
    swipeRight.numberOfTouchesRequired = 1;
    swipeRight.direction=UISwipeGestureRecognizerDirectionRight;
    [self.view addGestureRecognizer:(swipeRight)];
    }


-(void)screenSwipedRight
{
    NSLog(@"Screen was swiped to the right");
    CGFloat percentToRight = 1-(self.playerOne.position.x / self.view.bounds.size.width);
    NSTimeInterval timeToRight = self.horizontalRunSpeed * percentToRight;
    NSLog(@"Percent to right = %f",percentToRight);
    NSLog(@"Time to right = %f",timeToRight);
    SKAction *moveNodeRight = [SKAction moveToX:self.view.bounds.size.width-self.playerOne.size.width duration:timeToRight];
    [self.playerOne runAction:[SKAction sequence:@[moveNodeRight]]];
}

1 个答案:

答案 0 :(得分:0)

rdelmar在评论中回答了这个问题。引用如下:

“为什么不使用手势识别器的locationInView:属性来确定屏幕上初始触摸的位置,而不是添加左侧视图,而不是添加左侧视图?” - rdelmar

此解决方案将完美运行。使用locationInView属性将允许仅在屏幕的一侧识别手势。感谢rdelmar和nhgrif花时间帮忙。