从另一个类调用iOS pan和pinch识别器

时间:2015-07-20 11:32:46

标签: ios swift sprite-kit uigesturerecognizer

我正在使用Swift在iOS中开发SpriteKit应用程序,并且我已经为我的地图实现了平移和捏合手势。代码如下所示:

    //Zoom recognizer
    let pinch: UIPinchGestureRecognizer = UIPinchGestureRecognizer(target: self, action: Selector("pinch:"))
    view.addGestureRecognizer(pinch)

    // Move recognizer
    let pan: UIPanGestureRecognizer = UIPanGestureRecognizer(target: self, action: Selector("pan:"))
    view.addGestureRecognizer(pan)


func pinch(sender: UIPinchGestureRecognizer){

    var anchorPoint: CGPoint = sender.locationInView(sender.view)
    anchorPoint = convertPointFromView(anchorPoint)

    if (sender.state == UIGestureRecognizerState.Changed) {

        let anchorPointInMySKNode: CGPoint = world!.convertPoint(anchorPoint, fromNode: self)
        world!.setScale(world!.xScale * sender.scale)

        let mySKNodeAnchorPointInScene: CGPoint = self.convertPoint(anchorPointInMySKNode, fromNode: world!)
        let translationOfAnchorInScene = CGPointSubtract(anchorPoint, point2: mySKNodeAnchorPointInScene)

        world!.position = CGPointAdd(world!.position, point2: translationOfAnchorInScene)

        sender.scale = 1.0
    }
}

func pan(sender: UIPanGestureRecognizer){

    if(sender.state == UIGestureRecognizerState.Began){

        sender.setTranslation(CGPointZero, inView: sender.view)
    }

    else if (sender.state == UIGestureRecognizerState.Changed){

        var translation: CGPoint = sender.translationInView(sender.view!)
        translation = CGPointMake(-translation.x, translation.y)

        world!.position = CGPointSubtract(world!.position, point2: translation)
        sender.setTranslation(CGPointZero, inView: sender.view)
    }
}

代码工作正常,但目前它是用GameScene.swift类编写的,但是如果可以创建一个名为Gestures.swift的单独类并且只调用我想要的手势会更好。我尝试了几种方法,但没有一种方法可行。两个主要问题是如何解决GestureRecognizer函数中的选择器以及如何传递我在CaseScene.swift中初始化的案例世界中的父节点