Using Decreasing Variable as NSTimeInterval in swift - ios

I am trying to decrease a Double variable by 0.05 every second to speed up the function spawnEnemy() but I cannot find a way that works well. So, I am trying to pretty much "spawn" more enemies(UIButtons) in a shorter amount of time. Any help would be great and very appreciated. Thank you! My code below compiles fine but does not speed up the NSTimer controlling the function spawnEnemy()
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var scoreLabel: UILabel!
var points: Int = 0
func randomPoint() -> CGPoint {
let randomPoint: CGPoint = CGPoint(x:CGFloat(arc4random()%320),y:CGFloat(568-arc4random()%390))
return randomPoint
}
func randomColor() -> UIColor {
let red = CGFloat(drand48())
let green = CGFloat(drand48())
let blue = CGFloat(drand48())
return UIColor(red: red, green: green, blue: blue, alpha: 1.0)
}
func spawnEnemy() {
let enemy: UIButton = UIButton(frame: CGRect(x: 160, y: 160, width: 100, height: 100))
enemy.backgroundColor = randomColor()
enemy.center = randomPoint()
enemy.addTarget(self, action: Selector("buttonPushed:"), forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(enemy)
}
func buttonPushed(sender : UIButton) {
if sender.frame.height < 50 || sender.frame.width < 50 {
sender.frame = CGRectMake(sender.frame.origin.x, sender.frame.origin.y, 50, 50)
sender.backgroundColor = randomColor()
sender.center = randomPoint()
return
}
sender.backgroundColor = UIColor.blackColor()
points = points + 1
scoreLabel.textAlignment = .Center
scoreLabel.text = "\(points)"
scoreLabel.backgroundColor = UIColor.blackColor()
}
func decreaseDouble() -> Double {
var num: Double = 2.0
num = num - 0.05
return num
}
override func viewDidLoad() {
super.viewDidLoad()
NSTimer.scheduledTimerWithTimeInterval(decreaseDouble(), target: self, selector: Selector("spawnEnemy"), userInfo: nil, repeats: true)
NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("decreaseDouble"), userInfo: nil, repeats: false)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
Below is my new code. Any finals things or should this work? I also added a while statement so you can only receive points while the enemy is not black,otherwise you could just keep clicking on wherever enemies have been spawned(but were clicked) and keep getting points. However, now when i run the application two enemies are already spawned but i can still click on them(only being allowed to get two points)
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var scoreLabel: UILabel!
var points: Int = 0
func randomPoint() -> CGPoint {
let randomPoint: CGPoint = CGPoint(x:CGFloat(arc4random()%320),y:CGFloat(568-arc4random()%390))
return randomPoint
}
func randomColor() -> UIColor {
let red = CGFloat(drand48())
let green = CGFloat(drand48())
let blue = CGFloat(drand48())
return UIColor(red: red, green: green, blue: blue, alpha: 1.0)
}
func spawnEnemy() {
let enemy: UIButton = UIButton(frame: CGRect(x: 160, y: 160, width: 100, height: 100))
enemy.backgroundColor = randomColor()
enemy.center = randomPoint()
enemy.addTarget(self, action: Selector("buttonPushed:"), forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(enemy)
}
func buttonPushed(sender : UIButton) {
if sender.frame.height < 50 || sender.frame.width < 50 {
sender.frame = CGRectMake(sender.frame.origin.x, sender.frame.origin.y, 50, 50)
sender.backgroundColor = randomColor()
sender.center = randomPoint()
return
}
while sender.backgroundColor != UIColor.blackColor() {
points = points + 1
scoreLabel.textAlignment = .Center
scoreLabel.text = "\(points)"
scoreLabel.backgroundColor = UIColor.blackColor()
sender.backgroundColor = UIColor.blackColor()
}
delayTime -= 0.05
}
var delayTime: Double = 2.0
override func viewDidLoad() {
super.viewDidLoad()
delayTime = 2.0
NSTimer.scheduledTimerWithTimeInterval(2.0, target: self, selector: Selector("spawnEnemy"), userInfo: nil, repeats: false)
NSTimer.scheduledTimerWithTimeInterval(delayTime, target: self, selector: Selector("spawnEnemy"), userInfo: nil, repeats: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}

Repeating NSTimers always fire on the same interval once you start them.
If you want to use a decreasing interval then instead of a repeating timer I suggest use use a single "one-shot" timer (not 2 timers). Create the timer with repeats:false. Then in your timer method (spawnEnemy, in your case) decrement your time interval and use it to create a new timer (also with repeats:false) using the new, shorter interval and calling the same method.
Your decreaseDouble function isn't going to work as written. It will always return the same value of 2.0 - 0.05, since you set num to 2.0 each time the function called. Instead get rid of the decreaseDouble function. Create an instance variable delayValue and assign it a value (2.0, for example) in your viewDidLoad. Then just subtract 0.05 from it each time spawnEnemy is called, spawn a new enemy, and create a new timer if delayValue hasn't gotten too small. (When delayValue gets really small you're going to be spawning 10 enemies a second. Eventually delayValue will go to zero, and a timer interval should not be <= 0.0.

You have the right idea. I would use the repeating timer as a 'tick' and then keep two properties - One is the tick count and the other is the tick count before a new enemy is spawned. By decreasing the latter you can speed up the rate of spawning.
Something like this
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var scoreLabel: UILabel!
var points: Int = 0
var tickCount=0
var spawnRate=100 // Spawn every 10 seconds to start with
var spawnTimer:NSTimer!
override func viewDidLoad() {
super.viewDidLoad()
self.tickCount=self.spawnRate
self.spawnTimer=NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("tick"), userInfo: nil, repeats: true)
}
func tick() {
if (--tickCount == 0) {
self.spawnEnemy()
self.spawnRate=spawnRate - 2 // Change this to determine how quickly the spawn rate increases
self.tickCount=self.spawnRate
}
}
You can modify the tick rate and tick decrement amounts as required to give you the range you are after

Related

Fade image of button from one image to another via a float value

In my use case, I have a slider that moves from 0.0 to 1.0. When moving that slider I want a button's image to fade from one image to another smoothly. The button will only transition between two images. As one fades in, the other fades out and vice-versa.
There are answers on SO on how to change the image of a button over a fixed duration but I can't find something based on a changing float.
So is there a way to change the image of a button over a duration from one image to another based on a float that changes from 0.0 to 1.0?
EDIT:
For example, imagine a button that transitions smoothly from an image of a red star to a green star as you move the slider back and forth. (I know you could accomplish this other ways but I want to use two images)
Give this a shot. It is doing what you want I think. The trick is to set the layer speed to 0 and just update the timeOffset.
import UIKit
class ViewController: UIViewController {
lazy var slider : UISlider = {
let sld = UISlider(frame: CGRect(x: 30, y: self.view.frame.height - 60, width: self.view.frame.width - 60, height: 20))
sld.addTarget(self, action: #selector(sliderChanged), for: .valueChanged)
sld.value = 0
sld.maximumValue = 1
sld.minimumValue = 0
sld.tintColor = UIColor.blue
return sld
}()
lazy var button : UIButton = {
let bt = UIButton(frame: CGRect(x: 0, y: 60, width: 150, height: 150))
bt.center.x = self.view.center.x
bt.addTarget(self, action: #selector(buttonPress), for: .touchUpInside)
bt.setImage(UIImage(named: "cat1"), for: .normal)
return bt
}()
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(button)
self.view.addSubview(slider)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
addAnimation()
}
func addAnimation(){
let anim = CATransition()
anim.type = kCATransitionFade
anim.duration = 1.0
button.layer.add(anim, forKey: nil)
button.layer.speed = 0
button.setImage(UIImage(named: "cat2"), for: .normal)
}
#objc func sliderChanged(){
print("value \(slider.value)")
button.layer.timeOffset = CFTimeInterval(slider.value)
}
#objc func buttonPress(){
print("pressed")
}
}
Here is the result:
For Swift 4
//This is slider
#IBOutlet weak var mSlider: UISlider!
//Add Target for valueChanged in ViewDidLoad
self.mSlider.addTarget(self, action: #selector(ViewController.onLuminosityChange), for: UIControlEvents.valueChanged)
//called when value change
#objc func onLuminosityChange(){
let value = self.mSlider.value
print(value)
if value > 0.5 {
btnImage.imageView?.alpha = CGFloat(value)
UIView.transition(with: self.btnImage.imageView!,
duration:0.3,
options: .showHideTransitionViews,
animations: { self.btnImage.setImage(newImage, for: .normal) },
completion: nil)
}else{
btnImage.imageView?.alpha = 1 - CGFloat(value)
UIView.transition(with: self.btnImage.imageView!,
duration:0.3,
options: .showHideTransitionViews,
animations: { self.btnImage.setImage(oldImage, for: .normal) },
completion: nil)
}
}
Or Inset an Action directly via Storyboard/XIB
This is another workaround, since i tired with single button but couldn't achieve the result, so what i did is i took two buttons overlaying each other, with same size, constraints and each with separate image.
var lastSlideValue : Float = 0.0
#IBOutlet weak var slideImage: UISlider!
#IBOutlet weak var btnImageOverlay: UIButton!
#IBOutlet weak var btnSecondOverlayImage: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
btnImageOverlay.imageView?.alpha = 1.0
btnSecondOverlayImage.imageView?.alpha = 0.0
}
#IBAction func sliderValueChanged(_ sender: Any) {//UIControlEventTouchUpInside connected method
let sliderr = sender as? UISlider
let value = sliderr?.value
if lastSlideValue < (sliderr?.value ?? 0.0) {
btnSecondOverlayImage.imageView?.alpha = CGFloat(value!)
btnImageOverlay.imageView?.alpha = 1 - CGFloat(value!)
} else if lastSlideValue == sliderr?.value {
print("equal")
} else {
btnImageOverlay.imageView?.alpha = CGFloat(value!)
btnSecondOverlayImage.imageView?.alpha = 1 - CGFloat(value!)
}
}
#IBAction func userTouchedSlider(_ sender: Any) { //UIControlEventValueChanged connected method
let sliderr = sender as? UISlider
lastSlideValue = (sliderr?.value)!
}
You could use cross fade animations with single button, but binding it with slider is difficult task. Let me know if you need any assistance with the same.

making buttons change colors in swift

Does anyone know how to make buttons change colors in swift? I have rectangle shaped buttons with text inside and a hollow background and I want the hollow space to change colors every 3 seconds or so. Can anyone help, I would greatly appreciate it!
Can you try
var counter = 0
var pageChangeTimer: Timer?
let colors = [UIColor.red,UIColor.green,,,,,,,,,] //,,,, set more
pageChangeTimer = Timer.scheduledTimer( withTimeInterval: 3.0 , repeats: true) { [weak self] timer in
if counter == colors.count {
counter = 0
}
self.btn.backgroundColor = colors[counter]
counter += 1
}
Extending #Sh_Khan's answer by generating random colors instead of an array of colors. I hope this helps:
Generating random colors
var counter = 0
var pageChangeTimer: Timer?
pageChangeTimer = Timer.scheduledTimer( withTimeInterval: 3.0 , repeats: true) { [weak self] timer in
if counter == colors.count {
counter = 0
}
self.btn.backgroundColor = colors[counter]
counter += 1
}
func getRandomColor() -> UIColor{
//Generate between 0 to 1
let red:CGFloat = CGFloat(drand48())
let green:CGFloat = CGFloat(drand48())
let blue:CGFloat = CGFloat(drand48())
return UIColor(red:red, green: green, blue: blue, alpha: 1.0)
}
Try this
var net = Bool()
override func viewDidLoad() {
super.viewDidLoad()
net = true
var timer = Timer.scheduledTimer(timeInterval: 0.3, target: self, selector: #selector(self.update), userInfo: nil, repeats: true)
}
// update method
#objc func update() {
// Something cool
if net == true {
// changebtn is the outlet of UIButton
changebtn.backgroundColor = UIColor.blue
net = false
}else{
changebtn.backgroundColor = UIColor.black
net = true
}
}

Swift Ints and some Doubles working but not all Doubles

What I am trying to do is increase the rate that the method spawnEnemy() is called on, and it works well using the starred numbers as Ints, but I felt like it goes by way too quickly so I thought of using Doubles and using the decimal point. However, if I go into the tenths spot of subtracting an amount from spawnRate in
self.spawnRate=spawnRate - 1.0 (I use anything but 0) spawnEnemy() will only be called on once in the simulator then nothing happens. Any advice or suggestions would be great. Thank you!
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var scoreLabel: UILabel!
var points: Int = 0
var tickCount=0.0 // **
var spawnRate=15.0 // Spawn every 15 seconds to start with..... **
var spawnTimer:NSTimer!
override func viewDidLoad() {
super.viewDidLoad()
self.tickCount=self.spawnRate
self.spawnTimer=NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("tick"), userInfo: nil, repeats: true)
}
func tick() {
if (--tickCount == 0) { // **
self.spawnEnemy()
self.spawnRate=spawnRate - 0.5 // Change this to determine how quickly the spawn rate increases..... **
self.tickCount=self.spawnRate
}
}
func randomPoint() -> CGPoint {
let randomPoint: CGPoint = CGPoint(x:CGFloat(arc4random()%320),y:CGFloat(568-arc4random()%390))
return randomPoint
}
func randomColor() -> UIColor {
let red = CGFloat(drand48())
let green = CGFloat(drand48())
let blue = CGFloat(drand48())
return UIColor(red: red, green: green, blue: blue, alpha: 1.0)
}
func spawnEnemy() {
let enemy: UIButton = UIButton(frame: CGRect(x: 160, y: 160, width: 100, height: 100))
enemy.backgroundColor = randomColor()
enemy.center = randomPoint()
enemy.addTarget(self, action: Selector("buttonPushed:"), forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(enemy)
}
func buttonPushed(sender : UIButton) {
if sender.frame.height < 50 || sender.frame.width < 50 {
sender.frame = CGRectMake(sender.frame.origin.x, sender.frame.origin.y, 50, 50)
sender.backgroundColor = randomColor()
sender.center = randomPoint()
return
}
while sender.backgroundColor != UIColor.blackColor() {
points = points + 1
scoreLabel.textAlignment = .Center
scoreLabel.text = "\(points)"
scoreLabel.backgroundColor = UIColor.blackColor()
sender.backgroundColor = UIColor.blackColor()
}
}
}
I think what's happening is you're trying to test a double with the equality operator. The problem is that there's always a bit of complexity in how doubles are stored that makes it very difficult to compare them with equality. Instead you need to do something like this:
if (--tickCount <= 0) {
That way you catch it going negative for sure, otherwise it can go right past 0 and continue to count down.

Spawning UIView every second at random CGPoint in Swift

I am trying to "spawn" a UIView with a random UIColor as its background at a random CGPoint. I am using the code below which compiles fine with no bugs or anything but when it runs in the simulator I click start(the button on the first ViewController) but then go to ViewTwo but nothing happens(no "enemies" are spawned). Thank you for any help.
import UIKit
var randomPoint: CGPoint = CGPoint(x: Int(arc4random()%1000), y: Int(arc4random()%1000))
class ViewController: UIViewController {
#IBOutlet weak var startGameButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
class ViewTwo : UIViewController {
var timer = NSTimer()
func randomColor() -> UIColor {
let red = CGFloat(drand48())
let green = CGFloat(drand48())
let blue = CGFloat(drand48())
return UIColor(red: red, green: green, blue: blue, alpha: 1.0)
}
func spawnEnemy() {
let enemy: UIView = UIView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
enemy.backgroundColor = randomColor()
enemy.center = randomPoint
self.view.addSubview(enemy)
}
override func viewDidLoad() {
super.viewDidLoad()
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("spawnEnemy"), userInfo: nil, repeats: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
Your randomPoint needs to be recalculated in spawnEnemy, and is generating a random x y from 0 to 1000 (and should also be a float) It will likely be off the screen.

Game stops working when restart button clicked

I have just started programming this past week and have been trying to make a simple game app for IOS. Everything had worked properly regarding what I want the game to be doing when playing it. However, after I lose and get taken to my end scene, when I click the restart button, the app appears to take me back to the game scene but instead opens up a dark brown screen and just stays there for a few seconds before going back to the end scene. Then, if I click the restart button again after being taken back to the end scene, it repeats.
It also appears that how long the brown screen lasts is dependent on the sharkTimer with the fastest time interval. So if the fastest on is generating a shark every half a second, the brown screen lasts for half a second before transferring to the end scene.
The game is really simple as the character is a fish that swims up and down and the goal of the game to eat little things called food and to avoid other things called sharks that swim toward you.
Here is a link to my project:
https://www.dropbox.com/sh/z8o3iunz9rng6na/AACDGGOTR-QhqbQc402y4sgRa?dl=0
This is what I've got so far in my GameScene.swift file:
import SpriteKit
import UIKit
struct physicsCategory
{
static let shark: UInt32 = 1
static let food: UInt32 = 2
static let fish: UInt32 = 3
}
class GameScene: SKScene, SKPhysicsContactDelegate
{
var score = Int()
var scoreLabel = UILabel()
var fish = SKSpriteNode(imageNamed: "fish1 copy.png")
var shark = SKSpriteNode(imageNamed: "shark1 copy.png")
var food = SKSpriteNode(imageNamed: "fish game point copy.png")
override func didMoveToView(view: SKView)
{
physicsWorld.contactDelegate = self
self.scene?.backgroundColor = UIColor(red: 117/255.0, green: 208/255.0, blue: 224/255.0, alpha: 1.0)
fish.setScale(0.15)
fish.position = CGPointMake(self.frame.size.width * 0.1, self.frame.size.height * 0.5)
fish.physicsBody = SKPhysicsBody(rectangleOfSize: CGSizeMake(35, 40))
fish.physicsBody?.affectedByGravity = false
fish.physicsBody?.categoryBitMask = physicsCategory.fish
fish.physicsBody?.contactTestBitMask = physicsCategory.shark
fish.physicsBody?.contactTestBitMask = physicsCategory.food
fish.physicsBody?.dynamic = false
self.addChild(fish)
var sharkTimer = NSTimer.scheduledTimerWithTimeInterval(2.0, target: self, selector: Selector("SpawnShark"), userInfo: nil, repeats: true)
var sharkTimer2 = NSTimer.scheduledTimerWithTimeInterval(2.33, target: self, selector: Selector("SpawnShark"), userInfo: nil, repeats: true)
var sharkTimer3 = NSTimer.scheduledTimerWithTimeInterval(2.79, target: self, selector: Selector("SpawnShark"), userInfo: nil, repeats: true)
var foodTimer = NSTimer.scheduledTimerWithTimeInterval(2.0, target: self, selector: Selector("SpawnFood"), userInfo: nil, repeats: true)
scoreLabel.text = "\(score)"
scoreLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 20))
scoreLabel.backgroundColor = UIColor(red: 0.1, green: 0.1, blue: 0.1, alpha: 0.3)
scoreLabel.textColor = UIColor.whiteColor()
self.view?.addSubview(scoreLabel)
}
func SpawnShark()
{
var shark = SKSpriteNode(imageNamed: "shark1 copy.png")
shark.setScale(0.33)
var MinValue = self.size.height - self.size.height
var MaxValue = self.size.height
var SpawnPoint = UInt32(MaxValue - MinValue)
shark.position = CGPoint(x: self.size.width , y: CGFloat(arc4random_uniform(SpawnPoint)))
let action = SKAction.moveToX(-70, duration: 3.0)
shark.runAction(SKAction.repeatActionForever(action))
let actionDone = SKAction.removeFromParent()
shark.runAction(SKAction.sequence([action, actionDone]))
shark.physicsBody = SKPhysicsBody(rectangleOfSize: CGSizeMake(100, 20))
shark.physicsBody?.affectedByGravity = false
shark.physicsBody?.categoryBitMask = physicsCategory.shark
shark.physicsBody?.contactTestBitMask = physicsCategory.fish
shark.physicsBody?.dynamic = true
self.addChild(shark)
}
func SpawnFood()
{
var food = SKSpriteNode(imageNamed: "fish game point copy.png")
food.setScale(0.1)
var MinValue = self.size.height - self.size.height + 10
var MaxValue = self.size.height - 10
var SpawnPoint = UInt32(MaxValue - MinValue)
food.position = CGPoint(x: self.size.width , y: CGFloat(arc4random_uniform(SpawnPoint)))
let action = SKAction.moveToX(-70, duration: 5.0)
food.runAction(SKAction.repeatActionForever(action))
let actionDone = SKAction.removeFromParent()
food.runAction(SKAction.sequence([action, actionDone]))
food.physicsBody = SKPhysicsBody(rectangleOfSize: CGSizeMake(10, 10))
food.physicsBody?.affectedByGravity = false
food.physicsBody?.categoryBitMask = physicsCategory.food
food.physicsBody?.contactTestBitMask = physicsCategory.fish
food.physicsBody?.dynamic = true
self.addChild(food)
}
func didBeginContact(contact: SKPhysicsContact)
{
var firstBody: SKPhysicsBody = contact.bodyA
var secondBody: SKPhysicsBody = contact.bodyB
if (firstBody.categoryBitMask == physicsCategory.fish) && (secondBody.categoryBitMask == physicsCategory.food) ||
(firstBody.categoryBitMask == physicsCategory.food) && (secondBody.categoryBitMask == physicsCategory.fish)
{
CollisionWithFood(firstBody.node as! SKSpriteNode, food: secondBody.node as! SKSpriteNode)
}
else if (firstBody.categoryBitMask == physicsCategory.shark) && (secondBody.categoryBitMask == physicsCategory.fish) ||
(firstBody.categoryBitMask == physicsCategory.fish) && (secondBody.categoryBitMask == physicsCategory.shark)
{
CollisionWithFish(firstBody.node as! SKSpriteNode, fish: secondBody.node as! SKSpriteNode)
}
}
func CollisionWithFood(fish: SKSpriteNode, food: SKSpriteNode)
{
food.removeFromParent()
score++
scoreLabel.text = "\(score)"
}
func CollisionWithFish(shark: SKSpriteNode, fish: SKSpriteNode)
{
fish.removeFromParent()
scoreLabel.removeFromSuperview()
self.view?.presentScene(EndScene())
self.view?.presentScene(EndScene(), transition: SKTransition.crossFadeWithDuration(1.0))
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent)
{
for touch: AnyObject in touches
{
let location = touch.locationInNode(self)
fish.position.y = location.y
}
}
override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
for touch: AnyObject in touches
{
let location = touch.locationInNode(self)
fish.position.y = location.y
}
}
override func update(currentTime: CFTimeInterval)
{
/* Called before each frame is rendered */
}
}
My second file called EndScene.swift is where the program goes to if the shark gets you and the game ends. Its a white screen with a little restart button in the upper middle of the screen that when you press it, should take you back to the game scene, but instead takes you to a dark brown one.
Here is my EndScene.swift file:
import Foundation
import SpriteKit
class EndScene: SKScene
{
var restartButton: UIButton!
override func didMoveToView(view: SKView)
{
scene?.backgroundColor = UIColor.whiteColor()
restartButton = UIButton(frame: CGRect(x: 0, y: 0, width: view.frame.size.width / 3, height: 30))
restartButton.center = CGPoint(x: view.frame.size.width / 2, y: view.frame.size.width / 7)
restartButton.setTitle("Restart", forState: UIControlState.Normal)
restartButton.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Normal)
restartButton.addTarget(self, action: Selector("Restart"), forControlEvents: UIControlEvents.TouchUpInside)
self.view?.addSubview(restartButton)
}
func Restart()
{
self.view?.presentScene(GameScene(), transition: SKTransition.crossFadeWithDuration(0.3))
restartButton.removeFromSuperview()
}
}
You should add self.view to GameScene init when presenting the scene
func Restart()
{
self.view?.presentScene(GameScene(size: view.frame.size), transition: SKTransition.crossFadeWithDuration(0.3))
restartButton.removeFromSuperview()
}

Resources