Scrolling a SwiftUI Sprite View
SwiftUI provides a sprite view to show a SpriteKit scene in a SwiftUI app. Supply a SpriteKit scene to the sprite view.
struct ContentView: View {
@State var currentScene: SKScene = GameScene(size:
CGSize(width: 2048, height: 1536))
var body: some View {
SpriteView(scene: currentScene)
}
}
SwiftUI provides a scroll view to scroll content that won’t fit in the main SwiftUI view. Place the sprite view inside the scroll view to scroll the scene.
var body: some View {
ScrollView {
SpriteView(scene: currentScene)
}
}
If you build and run this code, you will notice the scroll view covers the sprite view so you can’t see the sprite view or interact with it. How do you keep the scroll view from blocking the sprite view?
Add a .frame
modifier to the sprite view.
var body: some View {
ScrollView {
SpriteView(scene: currentScene)
.frame(width: 768, height: 768)
}
}
If you want to scroll the scene horizontally and vertically, supply the scrolling directions in an array when creating the scroll view.
var body: some View {
ScrollView([.horizontal, .vertical]) {
SpriteView(scene: currentScene)
.frame(width: 768, height: 768)
}
}