FrankVIII
FrankVIII

Reputation: 128

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.

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. 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.

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?

As I understand it, in my viewDidLoad I must include something like:

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:

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.

Any guidance will be greatly appreciated!

Upvotes: 1

Views: 350

Answers (1)

Jsdodgers
Jsdodgers

Reputation: 5312

The syntax for the action in swift is #selector(methodName(params:))

(See 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:)))

Upvotes: 2

Related Questions