Search code examples
swiftxcodesprite-kitpagecontrol

How to use page controls in spritekit? (Programatically)


I am creating a game and I want to include a page control (the three dots on the bottom of the screen - I would post a picture but I need more reputation!). This is so the user knows what page they are on while they are flicking through the scenes. I have created my game using SpriteKit and I was wondering if there is a way to add this programtically (without the use of story boards).


Solution

  • In an iOS Game template Playground I was able to achieve this with the following code (first two lines are from the template, the rest is my addition):

    // Load the SKScene from 'GameScene.sks'
    let sceneView = SKView(frame: CGRect(x:0 , y:0, width: 640, height: 480))
    
    let pageControl = UIPageControl()
    pageControl.translatesAutoresizingMaskIntoConstraints = false
    pageControl.numberOfPages = 3
    pageControl.currentPage = 1
    sceneView.addSubview(pageControl)
    
    // Centre the control left-to-right
    pageControl.centerXAnchor.constraint(equalTo: sceneView.centerXAnchor).isActive = true
    // Place the control 20 points up from the bottom edge
    pageControl.bottomAnchor.constraint(equalTo: sceneView.bottomAnchor, constant: -20).isActive = true
    

    To be notified of interaction with the UIPageControl, register a handler for the event:

    pageControl.addTarget(thing, action: #selector(Thing.handlePagingEvent), for: .valueChanged)
    

    (Where thing is of type Thing - your app structure will determine which object that should logically be)

    This assumes you have a single SKView in which you present one of three SKScenes. If you actually have a UIScrollView containing three SKViews, then look to UIScrollView.indicatorStyle instead.