I've got problem with init my parameters in UIViewController. I've got a class:
class ViewController: UIViewController {
@IBOutlet var cardButtons: Array<UIButton>
var flipCount = 0
var game: CardMatchingGame
var backCardImage: UIImage
var frontCardImage: UIImage
required init(coder aDecoder: NSCoder) {
self.backCardImage = UIImage(named: "back")
self.frontCardImage = UIImage(named: "front")
self.game = CardMatchingGame(count: cardButtons.count, deck: createDeck())
super.init(coder: aDecoder)
}
@IBAction func touchCardButton(sender: UIButton) {
var cardButtonsArray = cardButtons as NSArray
var chosenButtonIndex = cardButtonsArray.indexOfObject(sender)
game.chooseCardAtIndex(chosenButtonIndex)
}
func createDeck() -> Deck {
return PlayingCardDeck()
}
}
but I've got a error in
count: cardButtons.count >> Variable 'self.cardButtons' used before being initialized/Property 'self.cardButtons' not initialized at super.init call
and
deck: createDeck() >> 'self' used before super.init call
How can I fix this to got properly initialized UIViewController?
Thank you for your help.
You want to override awakeFromNib
and access the outlet there, not in the initialiser.
"The nib-loading infrastructure sends an awakeFromNib message to each object recreated from a nib archive, but only after all the objects in the archive have been loaded and initialized. When an object receives an awakeFromNib message, it is guaranteed to have all its outlet and action connections already established."
So I suggest something like:
class ViewController: UIViewController {
@IBOutlet var cardButtons: Array<UIButton>!
var flipCount = 0
var game: CardMatchingGame!
var backCardImage: UIImage
var frontCardImage: UIImage
required init(coder aDecoder: NSCoder) {
self.backCardImage = UIImage(named: "back")
self.frontCardImage = UIImage(named: "front")
super.init(coder: aDecoder)
}
override func awakeFromNib() {
super.awakeFromNib()
self.game = CardMatchingGame(count: cardButtons.count, deck: createDeck())
}
@IBAction func touchCardButton(sender: UIButton) {
var cardButtonsArray = cardButtons as NSArray
var chosenButtonIndex = cardButtonsArray.indexOfObject(sender)
game.chooseCardAtIndex(chosenButtonIndex)
}
func createDeck() -> Deck {
return PlayingCardDeck()
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With