【发布时间】:2020-01-17 09:55:27
【问题描述】:
我最近在这里问了一个关于如何使用protocoldelegate 模式的问题:How do you use the Delegate Protocol Pattern with SpriteKit?
虽然我得到了一个让我走得很远的答案,但我并没有让它一直工作,我认为这与我没有(而且我不能这么认为)的事实有关更改SKViews 时使用相同的实例。让我解释一下。
我有一个 UIViewController 和两个 SKScenes。 UIViewController 通过旋转设备呈现两个scenes; landscape 加载 SKScene 1 和纵向加载 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
}
}
在SKScene1:
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 的新实例来加载另一个场景。
【问题讨论】:
-
我并不完全清楚你在哪里设置
myDelegate属性,但你应该注意到,每次旋转设备时,都会创建新场景并呈现它。每次呈现它时,您都必须将其属性设置为您需要的值,所以可能在这一步有问题
标签: swift sprite-kit delegates protocols