I want to use below lines but where should I write it?
Timer.scheduledTimer(timeInterval: 3.0, target: self, selector: #selector(function), userInfo: nil, repeats: true)
It depends what you want to achieve. If you want that slider automatically start when app loads, then put it in viewDidLoad().
If you want to start slider when you press some button, then you need to put this code inside the #IBAction function for that button.
Note: #objc function which is determining work of the slider is written separately, like in the example above.
var i=Int()
override func viewDidLoad() {
super.viewDidLoad()
Timer.scheduledTimer(timeInterval: 3.0, target: self, selector: #selector(imageChange), userInfo: nil, repeats: true)
// Do any additional setup after loading the view.
}
#objc func imageChange(){
self.imageView.image=images[i]
if i<images.count-1{
i+=1
}
else{
i=0
}
}
Related
I have this code that is suppossed to make my phone vibrate constantly. but it stops after 1 vibration. Is there something wrong with my timer?
var timer: Timer?
#IBAction func button1(_ sender: UIButton) {
AudioServicesPlayAlertSound(kSystemSoundID_Vibrate)
timer?.invalidate()
timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: Selector(("doaction")), userInfo: nil, repeats: true)
}
What did I do wrong? help? I am also using xcode with swift. and have an iphone 7 plus if that matters.
The timer does not stop vibrating after one round. The timer never vibrates.
What the timer does is to call the doaction method repeatedly. But the doaction method does not perform any vibration. Therefore the only vibration is the single one in button1.
The vibration is only happening when you tap the button, you need the vibration to happen in your "doaction" method:
var timer: Timer?
#IBAction func button1(_ sender: UIButton) {
doaction()
timer?.invalidate()
timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: Selector(("doaction")), userInfo: nil, repeats: true)
}
func doaction() {
AudioServicesPlayAlertSound(kSystemSoundID_Vibrate)
}
New to Swift here- I'm trying to achieve a simple segue operation after predefined times lapses. But for some reason my Xcode isn't recognizing the Timer and gives error "Timer module has no member named scheduledTimer". I couldn't find help anywhere.
CODE:
import UIKit
class ViewController: UIViewController {
let emptystring = String()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var time = Timer.scheduledTimer(timeInterval: 8.0, target: self, selector: #selector(changeview), userInfo: nil, repeats: false)
}
func changeview (){
self.performSegueWithIdentifier("GoToMain", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "GoToMain"){
let destination = (segue.destinationViewController as! UINavigationController).viewControllers[0] as! SecondView
destination.emptyString = emptystring
}
print("Segue Performed")
}
}
Picture also shows my entire code, including the error. NOTE: It's not my own code. I only followed the answer to question in following link:
Xcode Swift 3: Timer and Segue View Controller Error
Timer is a Swift 3 type, but judging from the rest of your method signatures, you appear to be using Swift 2. Use NSTimer in Swift 2.
Also, for future reference, in addition to the timeInterval typo (which you've now fixed), the third parameter is selector, not selecter.
So, in Swift 2:
NSTimer.scheduledTimerWithTimeInterval(8.0, target: self, selector: #selector(changeview), userInfo: nil, repeats: false)
Or in Swift 3:
Timer.scheduledTimer(timeInterval: 8.0, target: self, selector: #selector(changeview), userInfo: nil, repeats: false)
You have declared the first parameter as timerInterval but it should be timeInterval instead.
So change:
var time = Timer.scheduledTimer(timerInterval: 8.0, target: self, selecter: #selector(changeview), userInfo: nil, repeats: false
To:
var time = Timer.scheduledTimer(timeInterval: 8.0, target: self, selector: #selector(changeview), userInfo: nil, repeats: false)
Also note that with Swift 4, you have to add #objc to the selector you call after the timer expires, because the code that calls this selector is apparently still written in Objective-C.
So change:
func changeview()
to this:
#objc func changeview()
I want to access myTimer variable from startTimer() function inside my backBtnPressed() function. Basically i want to add this code myTimer.invalidate() inside my backBtnPressed() function. How can i achieve that?
func startTimer() {
var myTimer = Timer.scheduledTimer(timeInterval: 3.0,
target: self,
selector: #selector(scrollToNextCell),
userInfo: nil,
repeats: true)
}
#IBAction func backBtnPressed(_ sender: UIButton) {
audioPlayer.stop()
}
As it stands now, you cannot access myTimer variable outside startTimer(), because it is outside the scope. For that, you need to declare myTimer as a Class variable. Them, you need to initialize it, as you are doing, and them you can access whatever you want inside the Class. Also don't forget to call startTimer, or it will return nil.
It looks more or less like this:
class YourViewController: ViewController {
var myTimer: Timer?
//some of your functions here
//...
override func viewDidLoad() {
super.viewDidLoad()
//...
startTimer()
}
func startTimer() {
myTimer = Timer.scheduledTimer(timeInterval: 3.0,
target: self,
selector: #selector(yourFunction),
userInfo: nil,
repeats: true)
}
#IBAction func backBtnPressed(_ sender: UIButton) {
//do whatever you want
myTimer.invalidate()
}
}
Simple make your timer a property:
class MyClass {
var timer: Timer?
func startTimer() {
timer = Timer.scheduledTimer(timeInterval: 3.0, target: self, selector: #selector(scrollToNextCell), userInfo: nil, repeats: true)
}
#IBAction func backBtnPressed(_ sender: UIButton) {
audioPlayer.stop()
timer.//do something with timer
}
}
So I've got two timers, one that increases the score and one that spawns enemies. I used a notification to invalidate the timers, and then I'm using another one to recreate the timers. When I quit and then open the app, there are two sets of enemies being spawned on top of each other. I think timerRecreate = true and also the regular timers in GameScene are also being called.
GameViewController.swift file:
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("pauseTimers:"), name:UIApplicationWillResignActiveNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("startTimers:"), name:UIApplicationDidBecomeActiveNotification, object: nil)
}
func pauseTimers(notification : NSNotification) {
println("Observer method called")
timer.invalidate()
scoretimer.invalidate()
}
func startTimers(notification : NSNotification) {
println("Observer method called")
timerRecreate = true
}
Code for timers in GameScene.swift
override func didMoveToView(view: SKView) {
//Spawn timer for enemy blocks
timer = NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: Selector("spawnEnemies"), userInfo: nil, repeats: true)
//Timer for keeping score
scoretimer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("scoreCounter"), userInfo: nil, repeats: true)
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
if timerRecreate == true {
//Spawn timer for enemy blocks
timer = NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: Selector("spawnEnemies"), userInfo: nil, repeats: true)
//Timer for keeping score
scoretimer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("scoreCounter"), userInfo: nil, repeats: true)
timerRecreate = false
}
}
I think the problem is when you initially open the app, be that after quitting out of it or opening it for the first time, timerRecreate is set to true as well as the regular spawning of blocks so two sets of blocks are spawned at the same time. How can I fix this?
Fixed it! I hope...
Anyway heres what I did. I created another boolean called timerz and set it to false when the DidBecomeActive notification was made. At the same time, timeRecreate is set to true. This guarantees that both timer sets arent running at the same time. In the update function inside the if statement on whether timRecreate was true, I set timeRecreate to false and timerz to true. So the timers are recreated and then it switches back to to old way of spawning them. I also put this old method of spawning them inside an if statement on whether timerz was true or false.
So I have a label that counts 1 every second using an NSTimer. I made an app that has a few moving UIImages. However every time the timer counts one up, the view seemingly reloads and the UIImages go back to their original positions. Furthermore, the UIImages are not where I had placed them in the storyboard (I placed them outside the view so they could move inwards, but when I start the app it just shows them right there already. They move but only for one second then go back to their original positions). Same code works fine on the iPhone but doesn't work on an iPad. I think it has something to do with the constraints because the code is the same. Here's the timer code:
func counting() {
timerCount = timerCount + 1
timerLabel.text = "\(timerCount)"
}
override func viewDidLoad() {
super.viewDidLoad()
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("counting"), userInfo: nil, repeats: true)
// Do any additional setup after loading the view, typically from a override nib.
}
Here's the code for moving my UIImages:
func MoveWalls() {
FirstTimer = NSTimer.scheduledTimerWithTimeInterval(0.07, target: self, selector: Selector("FirstMoving"), userInfo: nil, repeats: true)
SecondTimer = NSTimer.scheduledTimerWithTimeInterval(0.007, target: self, selector:
Selector("SecondMoving"), userInfo: nil, repeats:true)
ThirdTimer = NSTimer.scheduledTimerWithTimeInterval(0.006, target: self, selector:
Selector("ThirdMoving"), userInfo: nil, repeats:true)
FourthTimer = NSTimer.scheduledTimerWithTimeInterval(0.005, target: self, selector:
Selector("FourthMoving"), userInfo: nil, repeats:true)
}
func FirstMoving() {
First.center = CGPointMake(First.center.x + 1, First.center.y)
}
func SecondMoving() {
Second.center = CGPointMake(Second.center.x - 1, Second.center.y)
}
func ThirdMoving() {
ThirdMoving.center = CGPointMake(Third.center.x, Third.center.y + 1)
}
func FourthMoving() {
Fourth.center = CGPointMake(Fourth.center.x, Fourth.center.y 1)
}
My constraints:
Two buttons that start and end the game (Centered horizontally).
The four UIImages (size ratio)
A timer (Top left) which for some reason resets the view with each count.
I had the exact same problem. I solved it by adding this code for each of the moveable views:
override func viewDidLoad() {
super.viewDidLoad()
self.imageView.translatesAutoresizingMaskIntoConstraints = true
self.imageView2.translatesAutoresizingMaskIntoConstraints = true
}