gpt4 book ai didi

ios - Swift - 初始化 UIViewController

转载 作者:搜寻专家 更新时间:2023-10-31 08:05:28 25 4
gpt4 key购买 nike

我在 UIViewController 中初始化我的参数时遇到问题。我有一个类:

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()
}

但是我有一个错误

count: cardButtons.count >> Variable 'self.cardButtons' used before being initialized/Property 'self.cardButtons' not initialized at super.init call

deck: createDeck() >> 'self' used before super.init call

如何解决这个问题以正确初始化 UIViewController?

感谢您的帮助。

最佳答案

您想覆盖 awakeFromNib 并在那里访问 socket ,而不是在初始化程序中。

“nib 加载基础结构向每个从 nib 文件中重新创建的对象发送一条 awakeFromNib 消息,但只有在文件中的所有对象都已加载和初始化之后。当一个对象收到 awakeFromNib 消息时,它保证有它所有的导出和行动连接都已经建立。”

所以我建议像这样:

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()
}
}

关于ios - Swift - 初始化 UIViewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25441622/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com