0

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?

2 Answers2

0

What is happening if you try gs.scoreLabel.text = "Test content" ?

Where are you setting up and filling the score variable?

regetskcob
  • 1,172
  • 1
  • 13
  • 35
  • The score variable is a global variable in the initial view controller, it works in the GameStartViewController but not in the view inside the view of the GameStartViewController – Mohamed Mohamed May 11 '16 at 06:40
0

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
}
Dejan Skledar
  • 11,280
  • 7
  • 44
  • 70