Boost-button delay - iphone

I am making a game with a boost button. Of course, just leaving it as enabled would allow the player to tap it constantly. So, I need a 20 second delay before it is possible to push the button again. Also, would it be possible to show this progression on the button, preferably on the button itself?

In the future please try to show what you have tried to solve your problem. However, since you are new I'm going to let it slide once!
This code uses a NSTimer that is called once per second. It will fire what ever code you specify for "Boost". It will also disable user interaction on your button until it has been 20 seconds from when the button was pressed at which point it will allow the user to press the button again, and finally, this code displays how many seconds remain until "Boost" can be used again on the titleLabel property of your button.
- (IBAction)buttonPressed:(id)sender
{
myTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(activateBoost) userInfo:nil repeats:YES];
}
- (void)activateBoost
{
if (myButton.userInteractionEnabled == YES) {
//Put your Boost code here!
}
if ([myButton.titleLabel.text intValue] == 0) {
[myTimer invalidate];
[myButton setTitle:#"20" forState:UIControlStateNormal];
myButton.userInteractionEnabled = YES;
}else{
myButton.userInteractionEnabled = NO;
int currentTime = [myButton.titleLabel.text intValue];
int newTime = currentTime - 1;
myButton.titleLabel.text = [NSString stringWithFormat:#"%d",newTime];
}
}
In order for the above code to work, you will need the declare a NSTimer named "myTimer" and a UIButton "myButton". You will also need to set the buttons initial text to "20".

Related

Scroll UISlider Automatically

So currently I have a UISlider in a UIViewcontroller that is meant to start animations within subviews when the user slides.. Basically when the user slides I have this battery with a filling in it that fills the empty battery image with a bar to indicate power within a cell, and the user can slide to see the energy the battery has at certain times of the day.
At the moment, when the View loads I would like the UISlider to AUTOMATICALLY start sliding from the beginning of the slider and scroll to the end within, lets say 5 seconds.
I implemented a loop that cycles through all the values of the uislider using this loop
for (int i = 0; i < [anObject count] - 2; i++)
{
sleep(.25);
NSUInteger index = (NSUInteger)(slider.value + 0.5); // Round the number.
[slider setValue:index animated:YES];
}
[anObject count] - 2 is equal to 62 at this time of day but will change and increment every 15 seconds because I'm fetching data from a server.
But that aside, why doesn't this work? The loop?
EDIT:
So heres what I did with NSTIMER
[NSTimer timerWithTimeInterval:0.25 target:self selector:#selector(animateSlider) userInfo:nil repeats:NO];
and animateSlider looks like this:
- (void)animateSlider:(NSTimer *)timer
{
NSLog(#"Animating");
NSUInteger index = (NSUInteger)(slider.value + 0.5); // Round the number.
[slider setValue:index animated:YES];
}
But no luck... Why isn't NSTimer "firing"..... I remmeber vaguely there was a method that FIRES an nstimer method but not sure if that's needed...
EDIT:
Ahh it does need "Fire"....
NSTimer *timer = [NSTimer timerWithTimeInterval:0.25 target:self selector:#selector(animateSlider) userInfo:nil repeats:NO];
[timer fire];
But for some reason it only fires once.... Any ideas ?
"for some reason it only fires once..."
If you changed the NSTimer set up to this:
NSTimer *timer =
[NSTimer scheduledTimerWithTimeInterval:0.25
target:self
selector:#selector(animateSlider:)
userInfo:nil
repeats:YES];
This would schedule the timer on the current run loop immediately.
And since the "repeats" parameter is "YES", you'd then repeat the timer every quarter second, until you invalidate the timer (which you should do when the ending condition is reached, like when the slider reaches its destination).
P.S. You'd need to change the selector method declaration of your timer's target slightly. According to Apple's documentation, "The selector must correspond to a method that returns void and takes a single argument. The timer passes itself as the argument to this method."
So declare "animateSlider" like this instead:
- (void)animateSlider: (NSTimer *) theTimer;

objective-c: Animate button before timer ends

I'm working on a very simple iPhone game that involves choosing the right colored button as many times in a row based on a randomized voice prompt. I have it set up so that if the button is one color and gets clicked, it always goes to a hard-coded color every time (e.g. if you click red, it always turns blue). The color change method is set up in an IBOutlet. I have a timer set up in a while loop, and when the timer ends it checks if the player made the right selection. The problem is that the button color change does not occur until after the timer runs out, and this causes a problem with the method used to check the correct answer. Is there a way to make this color change happen instantly? From what I've searched I know it has something to do with storyboard actions not occurring until after code executes, but I haven't found anything with using a timer. Here is a section of the method that calls the timer if the answer is correct:
BOOL rightChoice = true;
int colorNum;
NSDate *startTime;
NSTimeInterval elapsed;
colorNum = [self randomizeNum:middle];
[self setTextLabel:colorNum];
while (rightChoice){
elapsed = 0.0;
startTime = [NSDate date];
while (elapsed < 2.0){
elapsed = [startTime timeIntervalSinceNow] * -1.0;
NSLog(#"elapsed time%f", elapsed);
}
rightChoice = [self correctChoice:middleStatus :colorNum];
colorNum = [self randomizeNum:middle];
}
One of two things stood out
You're using a while loop as a timer, don't do this - the operation is synchronous.
If this is run on the main thread, and you code doesn't return, your UI will update. The mantra goes: 'when you're not returning you're blocking.'
Cocoa has NSTimer which runs asynchronously - it is ideal here.
So let's get to grips with NSTimer (alternatively you can use GCD and save a queue to an ivar, but NSTimer seems the right way to go).
Make an ivar called timer_:
// Top of the .m file or in the .h
#interface ViewController () {
NSTimer *timer_;
}
#end
Make some start and stop functions. How you call these is up to you.
- (void)startTimer {
// If there's an existing timer, let's cancel it
if (timer_)
[timer_ invalidate];
// Start the timer
timer_ = [NSTimer scheduledTimerWithTimeInterval:5.0
target:self
selector:#selector(onTimerFinish:)
userInfo:nil
repeats:NO];
}
- (void)onTimerFinish:(id)sender {
NSLog(#"Timer finished!");
// Clean up the timer
[timer_ invalidate];
timer_ = nil;
}
- (void)stopTimer {
if (!timer_)
return;
// Clean up the timer
[timer_ invalidate];
timer_ = nil;
}
And now
Put your timer test code in the onTimerFinish function.
Make an ivar that stores the current choice. Update this ivar when a choice is made and make the relevant changes to the UI. Call stopTimer if the stop condition is met.
In the onTimerFinished you can conditionally call and startTimer again if you desire.
Hope this helps!

Time elapsed button in the iphone sdk

How do you create a time elapsed button in objective-c iphone SDK. To be a little more specific, this button will show in text how much time has elapsed since you've been holding the button. So for the time to elapse you must still have a finger on the button, not letting go. Once you let go the timer should restart. Note: For the iphone, not mac.
Use these two methods for buttons events. touchDown is called when you press the button and touchUp will be called when you lift your finger from the button. Calculate the time difference between these two methods. Also you can start timer in touchDown and stop/restart it in touchUp.
//connect this action with Touch up inside
- (IBAction)touchUp:(id)sender {
NSLog(#"up");
}
//connect this to tocuh down
- (IBAction)touchDown:(id)sender{
NSLog(#"down");
}
first, set an int variable at your header file
#property int timerCount;
#property (nonatomic, strong)NSTimer *yourTimer;
dont forget to synthesize it at the implementation file
(if you're still on lower SDK, you can change "strong" to "retain")
and then make the button and it's function
UIButton *yourButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
[yourButton setTag:1];
[yourButton setBackgroundColor:[UIColor redColor]];
[yourButton addTarget:self action:#selector(buttonHoldDown) forControlEvents:UIControlEventTouchDown];
[yourButton addTarget:self action:#selector(buttonRelease) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:yourButton];
this way, you've add a button at x:0 y:0 on your view with red color, containing two action target which is touch down and up inside
when you touch the button, the buttonHoldDown function is triggered, and when u release the button, the buttonRelease function is triggered
and then, fill the function
-(void)buttonHoldDown
{
yourTimer = [NSTimer timerWithTimeInterval:1 target:self selector:#selector(timerStart) userInfo:nil repeats:NO];
timerCount = 0;
}
-(void)buttonHoldUp
{
NSLog(#"the timer stops at %d seconds", timerCount);
timerCount = 0;
[yourTimer invalidate];
}
-(void)timerStart
{
timerCount++;
}
this way, when you touch the button, the program creates a timer and revalue the int timerCount to 0, which will be increased as the timer ticks in the "timerStart" function.
as you release the button, the function will track your current timerCount record and print it on the system, and then stop the timer

iphone button pressed for 3 seconds goes to a different view

I have a button in my app that when pressed goes to a view
but I need that when pressed for 3 seconds it would go to a different view,
like when you are on ipad on safari and you keep pressed the url, and it shows a pop up with copy etc,
but I need that when pressed for 3 second it goes to another view...
hope this makes sense, I will explain better if not understood,
thank you so much!
pd, also how to make it show the pop up style window?
cheers!
Try setting an NSTimer property in your view controller. When the button's pressed, create the timer and assign it to your property. You can detect that moment with this:
[button addTarget:self action:#selector(startHoldTimer) forControlEvents:UIControlEventTouchDown];
and assign with this:
-(void) startHoldTimer {
self.myTimer = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:#selector(goToNewView:) userInfo:nil repeats:NO];
}
Then set an action to run on a canceled touch, or a touch up inside:
[button addTarget:self action:#selector(touchUp) forControlEvents:UIControlEventTouchUpInside];
[button addTarget:self action:#selector(cancelTimer) forControlEvents:UIControlEventTouchCancel];
and
//if timer fires, this method gets called
-(void) goToNewView {
[self cancelTimer];
[self loadSecondView];
}
// normal button press invalidates the timer, and loads the first view
-(void) touchUp {
[self cancelTimer];
[self loadFirstView];
}
//protected, just in case self.myTimer wasn't assigned
-(void) cancelTimer {
if (self.myTimer != nil)
if ([self.myTimer isValid]) {
[self.myTimer invalidate];
}
}
That should take care of it!
Use a UILongPressGestureRecognizer, added to the button with -addGestureRecognizer:—it'll handle timing the touch and fire an event when it recognizes that the button's been held down for a while. You might want to reconsider your interaction pattern, though—generally, things that can be long-pressed aren't buttons, they're actual pieces of data in a view, like an image or a link in Safari.
One possible approach would be to implement one of the touches events (I don't remember the name, but the method that fires when you touch down on the button), and schedule a timer to fire in three seconds. If the user lifts her finger before that time, cancel the timer and perform the normal button click. If the time does fire (i.e. 3 seconds have elapsed), ignore the touch up event and load your new view.

UILabel only displaying odd objects in NSArray

I have an int which defines the objectAtIndex, which gives it to the string, which then displays it in the UILabel, HOWEVER, when I modify the array (add a word to it in this case) when I have the UILabel go through the array it only displays the odd ones. I have done an NSLog and found out that it DOES PASS EVERY SINGLE THING to the string, but the Label isn't displaying every single one, it only does it the first time, then I modify the array, and it only does odd
edit: the code:
- (void) stuff {
NSArray *indivwords = [sentence componentsSeparatedByString:#" "];
count = [indivwords count]; //count=int
if (i < count) {
NSString *chunk = [indivwords objectAtIndex:i];
[word setText:chunk];
NSLog(chunk);
i++;
} else {
word.textColor = [UIColor greenColor];
[word setText:#"DONE"];
}
}
All of this is being controlled by an NSTimer, which sets it off based on a slider value. Also i is set to 0 in the IBAction
The IBAction code:
word.textColor = [UIColor whiteColor];
[timer invalidate];
i = 0;
speedd = (1/speed.value)*60;
timer = [NSTimer scheduledTimerWithTimeInterval:(speedd) target:self selector:#selector(stuff) userInfo:nil repeats:YES];
EDIT:
I fixed it! What I did was call this after i reached the count
-(void)stoptimer
{
[timer invalidate];
timer = [NSTimer scheduledTimerWithTimeInterval:(.01) target:self selector:#selector(empty) userInfo:nil repeats:YES];
}
empty is just a void with nothing in it, well, all I did was add a comment,
//don't look over here, nothing to see here, oh look at that
Somebody can close this if they want
You said the time interval of your NSTimer is controlled by a slider. Perhaps you are starting a new timer instance every time you change the slider value, so after a change you would have two timers running. The first one updates the label and increments i. The second one comes right after the first and finds i's value incremented, so it displays the next chunk instead of the current one.
Count the instances of your timer - NSLog the timer in the timer callback and compare the results - it may be that you're firing more than one.
My guess is that you have two different actions calling this method, when you think there should be one. I'd put a break point in there, and see if it stops where you think it should.