无法在 Swift 游乐场中向 SKScene 添加滑动识别器?

Posted

技术标签:

【中文标题】无法在 Swift 游乐场中向 SKScene 添加滑动识别器?【英文标题】:Unable to add swipe recognizer to SKScene in Swift playground? 【发布时间】:2017-03-18 23:14:41 【问题描述】:

好的,我对 Swift Playground 的工作方式还有些陌生,但我正在尝试将 Swift 3 中的滑动手势识别器添加到我的 Swift Playground 中。关注这个http://www.spritekitlessons.com/gesture-recognizer-with-sprite-kit-and-swift/我现在有:

func swipedRight(sender:UISwipeGestureRecognizer)
    print("swiped right")


func swipedLeft(sender:UISwipeGestureRecognizer)
    print("swiped left")


func swipedUp(sender:UISwipeGestureRecognizer)
    print("swiped up")


func swipedDown(sender:UISwipeGestureRecognizer)
    print("swiped down")


let degree = CGFloat(M_PI_2) / 90


class GameScene: SKScene 
    var selectedNode: SKNode?
    var shakeAction: SKAction?

    override func didMove(to view: SKView) 

        /* Setup your scene here */

        let swipeRight:UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: Selector(("swipedRight:")))
        swipeRight.direction = .right
        view.addGestureRecognizer(swipeRight)


        let swipeLeft:UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: Selector(("swipedLeft:")))
        swipeLeft.direction = .left
        view.addGestureRecognizer(swipeLeft)


        let swipeUp:UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: Selector(("swipedUp:")))
        swipeUp.direction = .up
        view.addGestureRecognizer(swipeUp)


        let swipeDown:UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: Selector(("swipedDown:")))
        swipeDown.direction = .down
        view.addGestureRecognizer(swipeDown)
    

let frame = CGRect(x: 0, y: 0, width: 1000, height: 600) //view size
let view = SKView(frame: frame)

let scene = GameScene(size: frame.size)
view.presentScene(scene)
PlaygroundPage.current.liveView = view

这可以编译,但是当我滑动时,我得到一个无法识别的选择器错误,即使我确实在选择器中包含了函数:

我也尝试将函数放在类中。如何向 Swift Playground SKScene 添加滑动识别器?

【问题讨论】:

【参考方案1】:

您将选择器作为字符串传递,如错误日志中所述,它们肯定有问题

尝试使用新的选择器语法 - #selector(methodName)

例子:

class ViewController: UIViewController 

    override func viewDidLoad() 
        super.viewDidLoad()

        /* Swift 3 */

        let swipe = UISwipeGestureRecognizer(target: self, action:#selector(handleSwipe))
        view.addGestureRecognizer(swipe)

    

    func handleSwipe() 
        print("Swiped!")
    

不推荐使用字符串作为选择器。 如果methodName() 方法不存在,则使用新的选择器语法,您将收到编译错误——您的应用不会因为“无法识别的选择器”而崩溃。

【讨论】:

以上是关于无法在 Swift 游乐场中向 SKScene 添加滑动识别器?的主要内容,如果未能解决你的问题,请参考以下文章

如何将 swift 文件与 SKscene 连接?

Swift Playground 无法在 iPad 上运行

Manifest.plist 文件 ipad swift 游乐场

无法在 Swift 操场上加载纹理图集?

从 UIViewController 呈现 SKScene - Swift

是否可以在 iPad Swift 游乐场应用程序中保存显示在文件应用程序中的文件