我正在使用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中初始化的案例世界中的父节点
答案 0 :(得分:1)
您需要使用委托。我在游戏中使用了这种性质(但是在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/