Ever need to just quickly present a few options to the user in a SpriteKit game? There are lots of menu options for UIKit-based iOS apps, but when it came time to add a simple, re-usable menu in my SpriteKit game, I couldn’t find what I needed.
Enter SKPopMenu: a fast, tile-based menu for SpriteKit written in Swift.
Download SKPopMenuExample Xcode project
Features
- Supports 1-6 menu items
- Customize each menu item with a color and a label or sprite.
Installation
- Open the SKPopMenuExample Xcode project, and drag and drop SKPopMenu.swift into your Xcode project
Usage
In your SKScene, add the following:
1 2 3 |
let pop = SKPopMenu(numberOfSections:6, sceneFrame: self.frame) self.addChild(pop) |
Note: If you choose an odd number of items, the top-most item will be fullscreen width.
To set all sections to the same color:
1 |
pop.setColor(SKColor.magentaColor()) |
To set a specific color to section 1:
1 |
pop.setSectionColor(1, color: SKColor.magentaColor()) |
To change the text label of section 3:
1 2 3 |
let myLabel = SKLabelNode() myLabel.text = “hello” pop.setSectionLabel(3, label:label) |
To add a sprite to section 5:
1 |
pop.setSectionSprite(5, sprite:SKSpriteNode(imageNamed:”pop”) |
To change the name of section 6:
1 |
pop.setSectionName(6, text:”Contact”) |
To show the menu:
1 |
pop.slideUp(0.2) // duration is NSTimeInterval |
To hide the menu:
1 |
pop.slideDown(0.2) // duration is NSTimeInterval |
Show/hide example:
1 2 3 4 5 6 7 |
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { if pop.isShowing { pop.slideDown(0.2) } else { pop.slideUp(0.2) } } |
Delegate methods (optional)
- Add the protocol to your SKScene’s class definition:
1 |
GameScene: SKScene, SKPopMenuDelegate {} |
- Remember to set pop.popMenuDelegate = self
To get notified when a section is tapped:
1 2 3 4 5 |
func sectionTapped(index:Int, name:String) { if pop.sections[index].name == "email" { // email section tapped } } |
To get notified when the menu has appeared/disappeared:
1 2 3 4 5 6 7 |
func popMenuDidAppear() { // pop menu appeared } func popMenuDidDisappear() { // pop menu... wait for it... disappeared 😱 } |
Download SKPopMenuExample Xcode project