I am novice programmer =)
Help me please with random generator.
I would like to seed the random number generator so that it won't be the same every time.
func randomteTxt() {
var arr_person = [String]();
arr_person.append("ГЕНЕРАЛ");
arr_person.append("С КОЛБОЙ");
arr_person.append("ШПИОН");
arr_person.append("АРХИМЕД");
arr_person.append("ШЕКСПИР");
arr_person.append("С ФОНАРЕМ");
arr_person.append("БАРОН");
arr_person.append("ДИПЛОМАТ");
let time = UInt32(NSDate().timeIntervalSinceReferenceDate)
srand(time)
greatperson.text = arr_person[Int( random()%(arr_person.count))];
You can use NSTimer for that like add this in your viewDidLoad method:
var timer = NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: Selector("randomteTxt"), userInfo: nil, repeats: true)
And you can invalidate it when you don't need it.
Related
Just a simple task, but I'm in trouble. Trying to make a different way but it fails.
How to init NSTimer with declared previously variable? Neither var nor let helps.
The initial value of a property (in your case: timer) cannot depend on another property of the class (in your case: interval).
Therefore you have to move the assigment timer = NSTimer(interval, ...) into a method of the
class, e.g. into viewDidLoad. As a consequence, timer has to be defined as an
optional or implicitly unwrapped optional.
Note also that Selector(...) takes a literal string as argument, not the method itself.
So this should work:
class ViewController: UIViewController {
var interval : NSTimeInterval = 1.0
var timer : NSTimer!
func timerRedraw() {
}
override func viewDidLoad() {
super.viewDidLoad()
timer = NSTimer(timeInterval: interval, target: self, selector: Selector("timerRedraw"), userInfo: nil, repeats: true)
// ...
}
// Other methods ...
}
Try:
var interval:NSTimeInterval = 1.0
var timer = NSTimer.scheduledTimerWithTimeInterval(interval, target: self, selector: "timerRedraw:", userInfo: nil, repeats: true)
pro-tip and hopefully an appreciated FYI: Swift functions should also start with lower case letters (i.e. "timerRedraw").
I am trying to create a NSTimer so that I can move a UIImageView down but
The NSTImer is having difficulty, saying first that this.
var timer = NSTimer.scheduledTimerWithTimeInterval(0.5, target:self(), selector: Selector ("mrockdown"), userInfo: nil, repeats: true)
is missing argument for parameter #1 in call. But when I remove the brackets from the target:self() it tells me
Cannot invoke 'scheduledTimerWIthTimerInterval' with an argument list of type '(Double, target: ViewController -> () -> ViewController, selector: Selector, userinfo: nil, repeates Bool.
What should I do?
The problem has to do with where you are saying this. It looks like you are trying to say this as part of a property declaration:
class ViewController {
var timer = ...
// ...
}
But you can't do that, because there is no self as far as a stored property is concerned. You need to declare the timer as an Optional and then initialize it later:
class ViewController {
var timer = NSTimer!
func someMethod {
timer = ...
}
}
Then you will remove the parentheses (they are wrong) and everything will compile just fine.
You can do this inside the function where you want to trigger the timer (i.e. viewDidLoad or some IBAction)
_ = Timer.scheduledTimer(timeInterval: yourInterval, target: self, selector: #selector(yourFunction), userInfo: nil, repeats: true)
That being said, to animate a view you should use this instead:
UIView.animate(withDuration: yourDuration) {
// set yourView's final position here
}
I'm trying to pass a UIButton with a NSTimer's userinfo. I've read every post on stackoverflow on NSTimers. I'm getting very close but can't quite get there. This post has helped
Swift NSTimer retrieving userInfo as CGPoint
func timeToRun(ButonToEnable:UIButton) {
var tempButton = ButonToEnable
timer = NSTimer.scheduledTimerWithTimeInterval(4, target: self, selector: Selector("setRotateToFalse"), userInfo: ["theButton" :tempButton], repeats: false)
}
the function the timer runs
func setRotateToFalse() {
println( timer.userInfo )// just see whats happening
rotate = false
let userInfo = timer.userInfo as Dictionary<String, AnyObject>
var tempbutton:UIButton = (userInfo["theButton"] as UIButton)
tempbutton.enabled = true
timer.invalidate()
}
I realise you've managed to fix this but I thought I would give you a little more information about using NSTimer. The correct way to access the timer object and hence user info is to use it like below. When initialising the timer you can create it like this:
Swift 2.x
NSTimer.scheduledTimerWithTimeInterval(4, target: self, selector: Selector("setRotateToFalse:"), userInfo: ["theButton" :tempButton], repeats: false)
Swift 3.x<
Timer.scheduledTimer(timeInterval: 1, target: self, selector:#selector(ViewController.setRotateToFalse), userInfo: ["theButton" :tempButton], repeats: false)
Then the callback looks like this:
func setRotateToFalse(timer:NSTimer) {
rotate = false
let userInfo = timer.userInfo as Dictionary<String, AnyObject>
var tempbutton:UIButton = (userInfo["theButton"] as UIButton)
tempbutton.enabled = true
timer.invalidate()
}
Therefore you don't need to keep a reference to the timer and avoid often nasty global variables where possible. You may run into an issue in swift if your class doesn't inherit from NSObject where it says there is no callback defined but this can be easily fixed by adding #objc at the beginning of the function definition.
macOS 10.12+ and iOS 10.0+ introduces a block based API of Timer which is a more convenient way
func timeToRun(buttonToEnable: UIButton) {
timer = Timer.scheduledTimer(withTimeInterval:4, repeats: false) { timer in
buttonToEnable.enabled = true
}
}
A one shot timer will be invalidated automatically after it fires.
An similar convenient way for a one shot timer is using GCD (DispatchQueue.main.asyncAfter)
func timeToRun(buttonToEnable: UIButton) {
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(4)) {
buttonToEnable.enabled = true
}
}
I was just going to post this as I read over it before I posted. I noticed that I had timer.invalidate() before userinfo so that's why it wasn't working. I will post it as it may help somebody else.
func setRotateToFalse(timer:NSTimer) {
rotate = false
timer.invalidate()
let userInfo = timer.userInfo as Dictionary<String, AnyObject>
var tempbutton:UIButton = (userInfo["theButton"] as UIButton)
tempbutton.enabled = true
}
Just a simple task, but I'm in trouble. Trying to make a different way but it fails.
How to init NSTimer with declared previously variable? Neither var nor let helps.
The initial value of a property (in your case: timer) cannot depend on another property of the class (in your case: interval).
Therefore you have to move the assigment timer = NSTimer(interval, ...) into a method of the
class, e.g. into viewDidLoad. As a consequence, timer has to be defined as an
optional or implicitly unwrapped optional.
Note also that Selector(...) takes a literal string as argument, not the method itself.
So this should work:
class ViewController: UIViewController {
var interval : NSTimeInterval = 1.0
var timer : NSTimer!
func timerRedraw() {
}
override func viewDidLoad() {
super.viewDidLoad()
timer = NSTimer(timeInterval: interval, target: self, selector: Selector("timerRedraw"), userInfo: nil, repeats: true)
// ...
}
// Other methods ...
}
Try:
var interval:NSTimeInterval = 1.0
var timer = NSTimer.scheduledTimerWithTimeInterval(interval, target: self, selector: "timerRedraw:", userInfo: nil, repeats: true)
pro-tip and hopefully an appreciated FYI: Swift functions should also start with lower case letters (i.e. "timerRedraw").
when i try to use integer variable as a timer interval in NSTimer in swift i get " extra argument "selector in call"
this is the code :
var count = 3
var Timer = NSTimer()
#IBAction func playButtonPressed(sender: AnyObject) {
Timer = NSTimer.scheduledTimerWithTimeInterval(count, target: self, selector: Selector("result"),userInfo: nil, repeats: true)
}
if i put 3 instead of count it works perfectly
i want to be able to give the user the advantage to set the interval himself.
The NSTimer.scheduledTimerWithTimeInterval takes a Double for that first parameter. Try using:
var count: Double = 3.0