从另一个 class 调用 iOS 平移和捏合识别器

Call iOS pan and pinch recognizer from another class

我正在使用 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 class 编写的,但是如果可以创建一个名为 Gestures.swift 的单独 class 并直接调用会更好我想要哪个手势。我尝试了几种方法,但其中 none 有效。两个主要问题是如何解决 GestureRecognizer 函数中的选择器以及如何传递父节点,在我的例子中 world 在 GameScene.swift

中初始化

您需要使用委派。我在我的游戏中使用过这种性质的东西(但在 obj-c 中)。代表团是要走的路。

以下是我推荐的一些资源。 https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Protocols.html

http://code.tutsplus.com/tutorials/swift-from-scratch-delegation-and-properties--cms-23445

https://www.youtube.com/watch?v=AHx4nE7EMic

http://swift.exomachina.com/swift-tutorial-8-from-one-scene-to-another-using-delegate-protocol/