简体   繁体   English

Spritekit和Swift 4中的UILongPressGestureRecognizer

[英]UILongPressGestureRecognizer in Spritekit and Swift 4

I am a complete newbie to programming and I am trying to learn how to make a simple iOS game using Spritekit and Swift 4. 我是编程的新手,我正在尝试学习如何使用Spritekit和Swift 4制作简单的iOS游戏。

So far, I have achieved some mild success, but I would like to add some further details to the game to make it a little more playable. 到目前为止,我已经取得了一些小成就,但是我想在游戏中添加更多细节,以使其更具可玩性。

I have added some actions to my GameScene so that when the user taps the screen, a Sprite execute an action. 我在GameScene中添加了一些动作,以便当用户点击屏幕时,Sprite会执行一个动作。 It works fine, but now I want to keep repeating that action if the user holds its finger on the screen . 它可以正常工作,但是现在,如果用户将手指放在屏幕上,我想继续重复该操作

I have read some posts about it, but they all seem to point to Objective-C or earlier versions of Swift that just pop a bunch of errors when testing and I am unable to get them working for me. 我已经阅读了一些有关它的文章,但是它们似乎都指向了Objective-C或更早的Swift版本,它们在测试时只会弹出很多错误,而我却无法让它们为我工作。

I know I am supposed to be using some instance of UILongPressGestureRecognizer but Apple's documentation seems rather confusing about how to initialise it or what to declare on action: Selector? 我知道我应该使用UILongPressGestureRecognizer某些实例,但是Apple的文档似乎对如何初始化它或在action: Selector?声明什么感到困惑action: Selector?

As I understand it, in my viewDidLoad I must include something like: 据我了解,在我的viewDidLoad我必须包含以下内容:

let longTapRecognizer = UILongPressGestureRecognizer(target: self, action: "handleLongPress:")
self.addGestureRecognizer(longTapRecognizer)

And then write a function (I am not sure if inside viewDidLoad as well) that handles the action: 然后编写一个处理动作的函数(我不确定在viewDidLoad中是否也包含):

func handleLongPress(recognizer: UIGestureRecognizer) {
    if recognizer.state == .began {
        print("Long press")
    }
}

As easy as this may sound, I simply cannot seem to understand how the action: is supposed to be declared or how to solve this. 听起来很简单,但我似乎根本无法理解该action:应该如何声明或如何解决。

Any guidance will be greatly appreciated! 任何指导将不胜感激!

The syntax for the action in swift is #selector(methodName(params:)) 快速操作的语法是#selector(methodName(params:))

(See https://developer.apple.com/documentation/swift/using_objective_c_runtime_features_in_swift ) (请参阅https://developer.apple.com/documentation/swift/using_objective_c_runtime_features_in_swift

Your gesture recognizer would be written as such: 您的手势识别器将这样写:

let longTapRecognizer = UILongPressGestureRecognizer(
  target: self,
  action: #selector(handleLongPress(recognizer:)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM