iosswiftskview

Edit UILabel From inside a View Frame


I have a UILabel and a View in a Stack View inside of the ViewController where I have a GameScene in that same View.

'''''''''''''''  <- GameStartViewController
'      L      '
'  '''''''''  '     L = UILabel
'  '   V   '  '     V = View Frame
'  '       '  '
'  '       '  '
'  '       '  '
'  '''''''''  '
'             '
'''''''''''''''

I'm trying to update the label which is the score from inside the view but I keep getting

fatal error: unexpectedly found nil while unwrapping an Optional value

Even though it is connected, I can't change color, set text, etc...

Code:

GameScene.swift

var gs: GameStartViewController!

override func didMoveToView(view: SKView) {
    physicsWorld.contactDelegate = self
    self.backgroundColor = UIColor.feelFreeToColor()
    gs.scoreLabel.text = "\(score)" // THIS DOES NOT WORK
}

GameStartViewController.swift

@IBOutlet weak var selfView: SKView!
@IBOutlet weak var scoreLabel: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()

    self.view.backgroundColor = UIColor.feelFreeToColor()
    self.initAdMobBanner()

    let scene: GameScene = GameScene(size: view.bounds.size)
    let skView = selfView
    scene.scaleMode = .AspectFill
    skView.presentScene(scene)

    scoreLabel.layer.addBorder(UIRectEdge.Bottom, color: UIColor.blackColor(), thickness: 3) // THIS WORKS
}

I can edit it from the view controller, but can't inside the view frame. How do I access it from inside the view frame?


Solution

  • Where are you setting the reference to the parent in your view (in your case to gs)?.

    Try setting the parent reference in your ViewController like this:

    override func viewDidLoad() {
        super.viewDidLoad()
    
        self.view.backgroundColor = UIColor.feelFreeToColor()
        self.initAdMobBanner()
    
        let scene: GameScene = GameScene(size: view.bounds.size)
    
        // Notice!
        scene.gs = self
    
        let skView = selfView
        scene.scaleMode = .AspectFill
        skView.presentScene(scene)
    
        scoreLabel.layer.addBorder(UIRectEdge.Bottom, color: UIColor.blackColor(), thickness: 3) // THIS WORKS
    }