make static function that brings UILabel

Hallo, i have main view conrtoller class, I would like to start the function in other UIview class.

When i make it "static func..." = there is an error - Instance member 'view' cannot be used on type 'BattleViewController'.

Thank You for help.


func setGameOverInfo() {

let gameOver = UILabel()

gameOver.text = "Game over\n" + "Your score: " + BattleViewController.updatedScore()

gameOver.numberOfLines = 2

gameOver.font = UIFont.systemFont(ofSize: 24)

gameOver.textColor = UIColor.white

gameOver.textAlignment = .center

view.addSubview(gameOver)

gameOver.translatesAutoresizingMaskIntoConstraints = false

let centerXGOConstraint = NSLayoutConstraint(item: gameOver, attribute: NSLayoutConstraint.Attribute.centerX, relatedBy: NSLayoutConstraint.Relation.equal, toItem: view, attribute: NSLayoutConstraint.Attribute.centerX, multiplier: 1, constant: 0)

let centerYGOConstraint = NSLayoutConstraint(item: gameOver, attribute: NSLayoutConstraint.Attribute.centerY, relatedBy: NSLayoutConstraint.Relation.equal, toItem: view, attribute: NSLayoutConstraint.Attribute.centerY, multiplier: 1, constant: -20 * scale)

view.addConstraints([centerXGOConstraint, centerYGOConstraint])

}

Accepted Reply

setGameOverInfo is not a static method in your code ; hence you cannot call with BattleFieldController.setGameOverInfo()


So, my advice is to:


- indide Alien class,


add at line 11

var parentVC : BattleViewController?


At line 102 or so, call

parentVC?.setGameOverInfo()


- inside BattleViewController, when you create an alien (I understand it is line 71 only, am I correct ?

If so, at line 72, add

alien.parentVC = self // Which is the BattleViewController in which you added the alien view.

Replies

setGameOverInfo is not a static method in your code ; hence you cannot call with BattleFieldController.setGameOverInfo()


So, my advice is to:


- indide Alien class,


add at line 11

var parentVC : BattleViewController?


At line 102 or so, call

parentVC?.setGameOverInfo()


- inside BattleViewController, when you create an alien (I understand it is line 71 only, am I correct ?

If so, at line 72, add

alien.parentVC = self // Which is the BattleViewController in which you added the alien view.

That is right. Now I understand everything. It was about strict BattleViewController as a parent VC. Not about UIVC. Thank You, You are my master. Say that I am quite good student 🙂 I would like some time to send You a pack of good polish small beer!

Wish you good continuation.

The pattern you learned here is close to the one you will use in delegation. Which is an important pattern to learn as well.


May be one day we will have a beer together.


In the meantime, enjoy yourself.