steff feyens steff feyens - 1 month ago 9
Swift Question

Updating label in other class with a function

I'm trying to display a message that is send from another class. I'm using a function to do this. But the problem is that the message doesn't display when I change the ViewController.

Setting the message:

StartViewController().showMessage(message: "Test Message", color: UIColor.green)


Displaying the message:

func showMessage(message: String, color: UIColor){

messageLabel = SKLabelNode(fontNamed: "Verdana")
messageLabel.text = message
messageLabel.fontSize = 15
messageLabel.fontColor = color
messageLabel.position = CGPoint(x: self.size.width / 2, y: self.size.height / 2)

self.addChild(messageLabel)
}


(These are 2 different file and ViewControllers)

Thanks for helping!

Answer

I think here there is a little confusion between UIKit and SpriteKit.

A ViewController has no member addChild, I think you would speak about SKNode object.

In SpriteKit , if you want to display a SKNode element or an objects that inherit SKNode, first of all you should cast your view as a SKView then instantiate and present an SKScene as explained for example in the "Hello world" project :

class GameViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        if let view = self.view as! SKView? {
            // Load the SKScene from 'GameScene.sks'
            if let scene = SKScene(fileNamed: "GameScene") {
                // Set the scale mode to scale to fit the window
                scene.scaleMode = .aspectFill
                // Present the scene
                view.presentScene(scene)
            }
            view.ignoresSiblingOrder = true
            view.showsFPS = true
            view.showsNodeCount = true
        }
    }
}
class GameScene: SKScene {
    override func didMove(to view: SKView) {
        print("This is my GameScene, here I could show my SKLabelNode")
    } 
}

Also, in SpriteKit you don't need to change viewController to display your elements, you can present a new SKScene or show directly a SKNode


To help you about your function you can do also:

func showMessage(message: String, color: UIColor,pos:CGPoint)->SKLabelNode{
        let messageLabel = SKLabelNode(fontNamed: "Verdana")
        messageLabel.text = message
        messageLabel.fontSize = 15
        messageLabel.fontColor = color
        return messageLabel
}

Usage:

let messagePos = CGPoint(x: self.size.width / 2, y: self.size.height / 2)
let messageLabel = showMessage(message:"Test Message", color: UIColor.green, pos:messagePos)
self.addChild(messageLabel)

Hope it can help you.

Comments