This is an inefficient way to do this as you are passing data through 3 different objects. However, going on with this methodology, the problem is the label's are not created yet inside
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let VC = segue.destination as? ThirdViewController {
VC.player1ScoreLabel.text = String(player1CurrentScore)
VC.player2ScoreLabel.text = String(player2CurrentScore)
VC.player3ScoreLabel.text = String(player3CurrentScore)
VC.player4ScoreLabel.text = String(player4CurrentScore)
}
}
See, the label isn't created yet. So, you are setting text
on aUILabel
that isn't initialized. Therefore, you need to create variables for the labels inside ThirdViewController
.
Third View Controller
class ThirdViewController: UIViewController {
@IBOutlet var player1ScoreLabel: UILabel!
@IBOutlet var player2ScoreLabel: UILabel!
@IBOutlet var player3ScoreLabel: UILabel!
@IBOutlet var player4ScoreLabel: UILabel!
var score0:Int!
var score1:Int!
var score2:Int!
var score3:Int!
override func viewDidLoad() {
super.viewDidLoad()
self.player1ScoreLabel.text = String(score0)
self.player2ScoreLabel.text = String(score1)
self.player3ScoreLabel.text = String(score2)
self.player4ScoreLabel.text = String(score3)
}
}
and change the segue in SecondViewController
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let VC = segue.destination as? ThirdViewController {
VC.score0 = player1CurrentScore
VC.score1 = player2CurrentScore
VC.score2 = player3CurrentScore
VC.score3 = player4CurrentScore
}
}
Another Way:
Let's create a singleton called Game
. Within this (assuming you only have 4 players) we can create 4 players that will never change. This allows us to create instances of players in one location and call upon them as necessary.
NOTE: A singleton can be misused EASILY.
https://cocoacasts.com/what-is-a-singleton-and-how-to-create-one-in-swift
https://cocoacasts.com/are-singletons-bad/
class Game {
static var score0:Int = 0
static var score1:Int = 0
static var score2:Int = 0
static var score2:Int = 0
}
Then, anywhere in your code you can access Game.score0, Game.score1.
CAUTION:
I would caution you to very carefully use singletons. You don't want everything with public access. You need to determine if this is good for you or not. Cheers.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…