gpt4 book ai didi

swift - 如何在委托(delegate)协议(protocol)模式中使用相同的实例?

转载 作者:行者123 更新时间:2023-11-30 10:27:49 25 4
gpt4 key购买 nike

我最近问了一个关于如何使用协议(protocol)委托(delegate)模式的问题:How do you use the Delegate Protocol Pattern with SpriteKit?

虽然我得到了一个让我走了很长一段路的答案,但我并没有让它一直有效,而且我认为这与我没有(而且我不能认为)这一事实有关更改 SKView 时使用相同的实例。让我解释一下。

我有一个 UIViewController 和两个 SKScenes。 UIViewController 通过旋转设备来呈现两个场景landscape 加载SKScene 1和portrait加载SKScene 2如下:

  override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
print("TRIGGERED")

if UIDevice.current.orientation.isLandscape {
print("Landscape")
presentView(name: "GameScene")
} else {
print("Portrait")
presentView(name: "GameScene2")
}
super.viewWillTransition(to: size, with: coordinator)

}

func presentView(name: String) {
if let view = self.view as! SKView? {
if let scene = SKScene(fileNamed: name) {
scene.scaleMode = .aspectFill
view.presentScene(scene)
}
view.ignoresSiblingOrder = true
view.showsFPS = true
view.showsNodeCount = true
}
}

SKScene 1中:

protocol MyProtocol {
func myProtocolFunc(someString: String)
}

class GameScene: SKScene{

var myDelegate: MyProtocol!

SKScene 2中:

class GameScene2: MyProtocol {
private var label: SKLabelNode?

func myProtocolFunc(someString: String) {
label = SKLabelNode(fontNamed: "Chalkduster")
label!.text = someString
label!.position = CGPoint(x: 0, y: 0)
addChild(label!)
}

但是,SKlabel 并未使用 delegate 值进行更新。正如我所说,我认为这是因为我在加载 SKScene 2 时创建了 scene 的新实例。并且该实例没有 delegate >。我不确定如何解决这个问题,因为我需要一个新的 SKScene 实例来加载其他场景。

最佳答案

关于swift - 如何在委托(delegate)协议(protocol)模式中使用相同的实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59784981/

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