How do you programmatically change view controllers? - ios

underneath my timerVar.invalidate(), i want have another view controller called "SinglePlayerGameOver" loaded but i can't work out how.Basically, when the timerCount becomes bigger than 10, i want a "gameOver" screen to appear.
import Foundation
import UIKit
class SinglePlayer: UIViewController {
var timerCount = 0
#IBOutlet weak var timer: UILabel!
var timerVar = NSTimer()
var taps = 0
func isCounting() {
timerCount += 1
timer.text = "\(timerCount)"
if timerCount >= 10 {
timerVar.invalidate()
}
}
override func viewDidLoad() {
super.viewDidLoad()
timerVar = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "isCounting", userInfo: nil, repeats:true)
}
}

You can use this fuction
self.presentViewController(SinglePlayerGameOver, animated: true, completion: nil)
if u have navigationController, then
self.navigationController?.pushViewController(SinglePlayerGameOver, animated: true);
put this code after check the time is over 10

Related

Time delay of texts in label in swift 3

I have a label. And I have 3 strings. I need to display text of 3 strings in the same label with delay of 10 seconds over a infinite loop. How can i solve this with simple animations in swift 3?
That's my solution. Just connect a UILabel to the IBOutlet
class ViewController: UIViewController {
#IBOutlet weak var textLabel: UILabel!
let messages = ["PROFESSIONAL AND BEST LEARNING CENTER","LEARNING TECHNOLOGY AND DESIGN IN A SMART WAY","EXPLORE YOUR SKILLS"]
let delayTime = 10.0
var counter = 0
override func viewDidLoad() {
super.viewDidLoad()
let timer = Timer.scheduledTimer(timeInterval: delayTime, target: self, selector: #selector(changeDisplayedText), userInfo: nil, repeats: true)
timer.fire()
}
func changeDisplayedText() {
textLabel.text = messages[counter % messages.count]
counter += 1
}
}
This will work for your, connect your outlet properly and declare those string in an array and load it with timer change.
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var label: UILabel!
var array = ["Aaaaaaaaaaa", "Bbbbbbbbbbb", "Ccccccccccc"]
var scrollIndex = 0
override func viewDidLoad() {
super.viewDidLoad()
let timer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(self.myDelayedFunction), userInfo: nil, repeats: true)
timer.fire()
}
func myDelayedFunction()-> Void {
let count = self.array.count
if scrollIndex == count {
scrollIndex = 0
}
if scrollIndex < count {
if count > 1{
self.label.text = array[scrollIndex]
self.scrollIndex += 1
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

Animation not animating in Swift 3 Xcode 8.1

When I run my application with the following code it only displays the first frame and doesn't loop through the other images.
class ViewController: UIViewController, UITextFieldDelegate {
var signUpMode = true
var activityIndicator = UIActivityIndicatorView()
#IBOutlet weak var emailText: UITextField!
#IBOutlet weak var passwordText: UITextField!
#IBOutlet weak var signIn: UIImageView!
//Animated sign in
var counter = 0
var animationStart = false
var timer = Timer()
func animateSignIn() {
signIn.image = UIImage(named: "frame_\(counter)_delay-0.04s.gif")
counter += 1
if counter == 128 {
counter = 0
}
}
func animation (){
if animationStart == true {
timer = Timer.scheduledTimer(timeInterval: 0.04, target: self, selector: #selector(ViewController.animateSignIn), userInfo: nil, repeats: true)
}
}
Then I set animationStart to true:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//remove root view controller navigation bar
self.navigationController?.navigationBar.isHidden = true
animationStart = true
}
Where did you call the function animation()?
I think viewDidLoad should look like this
override func viewDidLoad() {
super.viewDidLoad()
//remove root view controller navigation bar
self.navigationController?.navigationBar.isHidden = true
animationStart = true
animation() //call animation
}

Keep updating NSTimer label after segue

I have a number of initial settings in the viewDidLoad:
countDownLabel.alpha = 1
countDownLabel.text = "01:30"
swipeLeft.alpha = 0
swipeRight.alpha = 0
pressPlayToStartOr.alpha = 0
swipeToChangeTheSeq.alpha = 0
countDownPauseLbl.alpha = 0
I have an NSTimer (I've put func update () of the timer inside inside viewDidLoad as well, while it is triggered by a UIButton outside viewDidLoad). The timer continues running when I segue from the UI View Controller. When I segue back to the Timer View Controller, I can hear the sound of the timer running, but the Timer View Controller is refreshed to it's initial state and you can run the timer again so that they overlap. The programmatic segue after the timer finishes doesn't work in this case. I understand that I may have used the wrong approach, but hope it can be fixed. How can I make the label update, regardless of where I'am at in the app.
The effect:
In SingletonTimer.swift:
//
// SingletonTimer.swift
// testSwiftUITextField
//
// Created by leo on 2016/12/17.
// Copyright © 2016年 leo. All rights reserved.
//
import UIKit
class SingletonTimer: NSObject {
private static let sharedInstance = SingletonTimer()
class var sharedSingletonTimer:SingletonTimer {
return sharedInstance
}
var timeCount:Int = 100
func countDown() {
timeCount -= 1
timer_closure(timeCount)
}
lazy var timer:Timer = {
var timer:Timer
if #available(iOS 10.0, *) {
timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true, block: { (timer) in
self.countDown()
})
} else {
// Fallback on earlier versions
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(countDown), userInfo: nil, repeats: true)
}
return timer
}()
var timer_closure:(Int)->Void = { (count) in
}
}
In ViewController.swift:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
}
In ViewController2.swift:
import UIKit
class ViewController2: UIViewController {
#IBOutlet weak var label: UILabel!
var timer:Timer? = nil
override func viewDidLoad() {
super.viewDidLoad()
timer = SingletonTimer.sharedSingletonTimer.timer
SingletonTimer.sharedSingletonTimer.timer_closure = { (timeCount) in
print("\(timeCount)")
self.label.text = "\(timeCount)s !"
}
if timer != nil {
timer?.fire()
}
}
}

Swift Run An NSTimer Automatically

I'm making an app and using NSTimer to make the timer in my app.But I need the NSTimer to run when the scene start.I have two scene in my app a homescreen and the app it's self here is my code viewcontroller.swift (The second scene the first scene in empty) And btw it's my 3 day using swift and i'm in middle school ;).
import UIKit
var Number = 2
var Answer = Number * 2
var score = 0
var scorelabel = "Score: "
var Timer = NSTimer()
var Counter = 10
class SecondViewController: UIViewController {
#IBOutlet weak var RightAndWrongLabel: UILabel!
#IBOutlet weak var TimerLabel: UILabel!
#IBOutlet weak var RightAndWrong: UIImageView!
#IBOutlet weak var ScoreIabel: UILabel!
#IBOutlet weak var UserInputAnswer: UITextField!
#IBOutlet weak var Question: UILabel!
#IBOutlet weak var TimerOut: UIImageView!
var seconds = 0
var timeison = true
#IBAction func ConfirmAnswer(sender: AnyObject) {
let UserAnswer = Int(UserInputAnswer.text!)
if UserAnswer == Answer {
print("Your right")
Number += 2
score += 1
ScoreIabel.text = "Score: \(score)"
Question.text = "\(Number) x 2"
UserInputAnswer.text = ""
Answer = Number * 2
RightAndWrong.image = UIImage(named: "Label")
RightAndWrongLabel.hidden = false
RightAndWrongLabel.text = "Right!"
RightAndWrongLabel.textColor = UIColor(red: 0, green: 225, blue: 0, alpha: 1)
} else {
UserInputAnswer.text = ""
RightAndWrong.image = UIImage(named: "Label")
RightAndWrongLabel.hidden = false
RightAndWrongLabel.text = "Wrong!"
RightAndWrongLabel.textColor = UIColor(red: 225, green: 0, blue: 0, alpha: 1)
}
}
func DisplayTimer() {
Timer = NSTimer.scheduledTimerWithTimeInterval(1, target:self, selector: Selector("updateCounter"), userInfo: nil, repeats: true)
}
func updateTimer(){
TimerLabel.text = String(Counter--)
}
override func viewDidLoad() {
super.viewDidLoad()
UserInputAnswer.keyboardType = UIKeyboardType.NumberPad
RightAndWrongLabel.hidden = true
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
3
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
Swift 2.x :
func DisplayTimer() {
Timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target:self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
}
func updateTimer() {
if Counter != 0 { TimerLabel.text = "\(Counter -= 1)"
} else {
Timer.invalidate()
// call a game over method here...
}
}
override func viewDidLoad() {
super.viewDidLoad()
...
// start the timer when this controller shows up
DisplayTimer()
TimerLabel.text = "\(Counter)"
...
}
If you want to start your timer when the scene loads call DisplayTimer() under
override func viewDidLoad() when the view is loaded
Also if you want to update your label every second, the selector in your NSTimer is calling updateCounter not updateTimer

Swift: How to increment an element in an array

I am trying to display different text within a label after a period of time using a timer, but cant increment the element of my custom type array.
Here is the code:
import UIKit
class WorkWorkoutViewOne: UIViewController {
#IBOutlet weak var exerciseTitle: UILabel!
#IBOutlet weak var timerLabel: UILabel!
#IBOutlet weak var instructionsLabel: UILabel!
#IBOutlet weak var exerciseImage: UIImageView!
var counter = 15
var timer: NSTimer?
var workoutExercisesShuffled = [Exercise]()
override func viewDidLoad() {
super.viewDidLoad()
let image: UIImage = workoutExercisesShuffled[0].filename!
exerciseImage.image = image
let titleLabel = workoutExercisesShuffled[0].name
exerciseTitle.text = titleLabel
let instructionsTitle = workoutExercisesShuffled[0].instructions
instructionsLabel.text = instructionsTitle
var timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "timerAction", userInfo: nil, repeats: true)
}
var timerTwo: NSTimer?
var counterTwo = 15
func timerAction() {
--counter
timerLabel.text = "\(counter)"
if (counter == 0) {
timer?.invalidate()
let image: UIImage = workoutExercisesShuffled[1].filename!
exerciseImage.image = image
let titleLabel = workoutExercisesShuffled[1].name
exerciseTitle.text = titleLabel
let instructionsTitle = workoutExercisesShuffled[1].instructions
instructionsLabel.text = instructionsTitle
timerLabel.text = "\(counterTwo)"
var timerTwo = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "timerActionTwo", userInfo: nil, repeats: true)
}
}
Repeating this method using timerThree, timerFour etc. seems clumbsy and unnecessary, so would like a way to increment the array values rather than having to call seperately in different functions.
Try this, it uses two methods and an index.
Workflow
Initially index is set to 0 and counter is set to 15.
updateExercise() is called.
The exercise UI is updated.
If index is 0 the timer is created.
timerAction() is called after the timer fires.
The counter is decremented and the counter label is updated.
If counter is 0 and index is equal to the number of exercises -1 the timer is invalidated.
If counter is 0 and index < number of exercises -1 index is incremented, counter is reset to 15 and updateExercise() is called again.
var counter = 15
var index = 0
var timer: NSTimer?
var workoutExercisesShuffled = [Exercise]()
override func viewDidLoad() {
super.viewDidLoad()
updateExercise()
}
func updateExercise() {
let image: UIImage = workoutExercisesShuffled[index].filename!
exerciseImage.image = image
let titleLabel = workoutExercisesShuffled[index].name
exerciseTitle.text = titleLabel
let instructionsTitle = workoutExercisesShuffled[index].instructions
instructionsLabel.text = instructionsTitle
if index == 0 {
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "timerAction", userInfo: nil, repeats: true)
}
}
func timerAction() {
counter -= 1
timerLabel.text = "\(counter)"
if (counter == 0) {
if index == workoutExercisesShuffled.count - 1 {
timer!.invalidate()
timer = nil
} else {
index += 1
counter = 15
updateExercise()
}
}
}
I did not test this, but it should work.
import UIKit
class WorkWorkoutViewOne: UIViewController {
#IBOutlet weak var exerciseTitle: UILabel!
#IBOutlet weak var timerLabel: UILabel!
#IBOutlet weak var instructionsLabel: UILabel!
#IBOutlet weak var exerciseImage: UIImageView!
var count = 15
var index = 0
var timer: NSTimer
var countdown: NSTimer
var workoutExercisesShuffled = [Exercise]()
override func viewDidLoad() {
super.viewDidLoad()
// TODO: load your exercises
var timer = NSTimer.scheduledTimerWithTimeInterval(15, target: self, selector: "displayNewExercise", userInfo: nil, repeats: true)
}
func displayNewExercise() {
countdown = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "displayCountdown", userInfo: nil, repeats: true)
if (index < workoutExercisesShuffled.count) {
exerciseImage.image = workoutExercisesShuffled[index].filename!
exerciseTitle.text = workoutExercisesShuffled[index].name
instructionsLabel.text = workoutExercisesShuffled[index].instructions
++index
}
else {
timer.invalidate()
countdown.invalidate()
}
}
func displayCountdown() {
if(count > 0) {
countDownLabel.text = String(--count)
}
else {
countdown.invalidate()
count = 15
}
}
}
Don't repeat yourself. A certain task can be done only by one function, the code for this particular task must not be elsewhere.

Resources