Can you add a UIButton be used as the UI for a SKSpriteNode?

42 views Asked by At

I have UIButton that I created with custom UI properties and I want to add animations to it where it has a gravity and falls downwards using SpriteKit. Is it possible to SKSpriteNode support my UIButton as its / is it possible to combine SKSpriteNodes and UIViews at all?

1

There are 1 answers

0
Just an user On

For using the UIKit in SpriteKit use these functions using the view of a SKScene:

import SpriteKit
import UIKit

class Scene: SKScene {
    var button: UIButton = UIButton()

    //Adds the button to the view.
    func addButton() {
        if self.view != nil {
            self.view?.addSubView(button)
        }
    }
    ///IMPORTANT function when moving from view to other view for example.
    func removeButton() {
        if self.view != nil {
            //Removes the button from its super.view
            self.button.removeFromSuperview()
        }
    }
}

The second function is very important, because if you don’t use it when changing the scene, the subviews you added will not delete.

For more information, visit https://developer.apple.com/documentation/uikit/uiview/1622616-addsubview#managing-the-view-hierarchy

Btw, UIKit and SpriteKit use different coordinates methods, be careful.