didRotate(from:)
自iOS 8.0以来已弃用,因此我们将使用新方法。
每次旋转发生时,您需要告诉GameViewController通知当前场景。
1、CanReceiveTransitionEvents协议
让我们定义一个协议,说明conform类型(我们的场景)可以接收旋转事件
protocol CanReceiveTransitionEvents {
func viewWillTransition(to size: CGSize)
}
2、使我们的场景符合CanReceiveRotationEvents
现在让我们将我们自己的SKScene与协议相一致
class GameScene: SKScene, CanReceiveTransitionEvents {
func viewWillTransition(to size: CGSize) {
// this method will be called when a change in screen size occurs
// so add here your code
}
}
如果有多个场景,只需对每个场景重复。
3、ViewController应通知场景每次旋转
最后,让控制器在每次检测到旋转时调用相关的场景方法
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
guard
let skView = self.view as? SKView,
let canReceiveRotationEvents = skView.scene as? CanReceiveTransitionEvents else { return }
canReceiveRotationEvents.viewWillTransition(to: size)
}
就是这样。