Time elapsed button in the iphone sdk - iphone

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

Related

While button is being pressed

How do i set up a button (IBAction and UIButton attached) to continue to run the IBAction or a function while the button is being pressed, running a functioning continuously until the button is let up.
Should i attach a value changed receiver?
Simple question, but I can't find the answer.
[myButton addTarget:self action:#selector(buttonIsDown) forControlEvents:UIControlEventTouchDown];
[myButton addTarget:self action:#selector(buttonWasReleased) forControlEvents:UIControlEventTouchUpInside];
- (void)buttonIsDown
{
//myTimer should be declared in your header file so it can be used in both of these actions.
NSTimer *myTimer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:#selector(myRepeatingAction) userInfo:nil repeats:YES];
}
- (void)buttonWasReleased
{
[myTimer invalidate];
myTimer = nil;
}
Add a dispatch source iVar to your controller...
dispatch_source_t _timer;
Then, in your touchDown action, create the timer that fires every so many seconds. You will do your repeating work in there.
If all your work happens in UI, then set queue to be
dispatch_queue_t queue = dispatch_get_main_queue();
and then the timer will run on the main thread.
- (IBAction)touchDown:(id)sender {
if (!_timer) {
dispatch_queue_t queue = dispatch_get_global_queue(
DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
// This is the number of seconds between each firing of the timer
float timeoutInSeconds = 0.25;
dispatch_source_set_timer(
_timer,
dispatch_time(DISPATCH_TIME_NOW, timeoutInSeconds * NSEC_PER_SEC),
timeoutInSeconds * NSEC_PER_SEC,
0.10 * NSEC_PER_SEC);
dispatch_source_set_event_handler(_timer, ^{
// ***** LOOK HERE *****
// This block will execute every time the timer fires.
// Do any non-UI related work here so as not to block the main thread
dispatch_async(dispatch_get_main_queue(), ^{
// Do UI work on main thread
NSLog(#"Look, Mom, I'm doing some work");
});
});
}
dispatch_resume(_timer);
}
Now, make sure to register for both touch-up-inside and touch-up-outside
- (IBAction)touchUp:(id)sender {
if (_timer) {
dispatch_suspend(_timer);
}
}
Make sure you destroy the timer
- (void)dealloc {
if (_timer) {
dispatch_source_cancel(_timer);
dispatch_release(_timer);
_timer = NULL;
}
}
UIButton should call a starting method with touchDown event and call ending method with touchUpInside event

Boost-button delay

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".

Showing a subview temporary

What I am trying to achieve is showing a view during a couple of seconds without user intervention. Is the same effect as the ringer volume view that appears when pressing the volume controls on iphone:
I have a scroll view with an image, taping in the image, sound begin to play, another tap and it pauses. I would like to implement the above effect just to inform of the action (showing a play/pause images).
I hope that I have explained the problem perfectly.
Many thanks for your help.
Regards
Javi
Assume you have some class inherited from UIViewController. You can use the code below:
const int myViewTag = 10001;
const int myInterval = 1; // define the time you want your view to be visible
- (void)someAction {
//this could be your `IBAction` implementation
[self showMyView];
[NSTimer scheduledTimerWithTimeInterval:myInterval
target:self
selector:#selector(hideMyView)
userInfo:nil
repeats:NO];
}
- (void) showMyView {
//you can also use here a view that was declared as instance var
UIView *myView = [[[UIView alloc] initWithFrame:CGRectMake(100, 100, 120, 120)] autorelease];
myView.tag = myViewTag;
[self.view addSubview:myView];
}
- (void) hideMyView {
//this is a selector that called automatically after time interval finished
[[self.view viewWithTag:myViewTag] removeFromSuperview];
}
You can also add some animations here but this is another question :)

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.

How to delay while retaining a responsive GUI on Cocoa Touch?

Basically, I have an array of buttons I want to iterate and highlight (among other things) one after another, with a delay in-between. Seems like an easy task, but I can't seem to manage to get it to work cleanly while still being responsive.
I started out with this:
for MyButton *button in buttons {
[button highlight];
[button doStuff];
usleep(800000); // Wait 800 milliseconds.
}
But it is unresponsive, so I tried using the run loop instead.
void delayWithRunLoop(NSTimeInterval interval)
{
NSDate *date = [NSDate dateWithTimeIntervalSinceNow:interval];
[[NSRunLoop currentRunLoop] runUntilDate:date];
}
for MyButton *button in buttons {
[button highlight];
[button doStuff];
delayWithRunLoop(0.8); // Wait 800 milliseconds.
}
However, it is also unresponsive.
Is there any reasonable way to do this? It seems cumbersome to use threads or NSTimers.
NSTimer will be perfect for this task.
The timer's action will fire ever x seconds, where x is what you specify.
The salient point is that this doesn't block the thread it runs on. As Peter said in the comments for this answer, I was incorrect in saying the timer waits on a separate thread. See the link in the comment for details.
Nevermind, Jasarien was right, NSTimer is perfectly suitable.
- (void)tapButtons:(NSArray *)buttons
{
const NSTimeInterval waitInterval = 0.5; // Wait 500 milliseconds between each button.
NSTimeInterval nextInterval = waitInterval;
for (MyButton *button in buttons) {
[NSTimer scheduledTimerWithTimeInterval:nextInterval
target:self
selector:#selector(tapButtonForTimer:)
userInfo:button
repeats:NO];
nextInterval += waitInterval;
}
}
- (void)tapButtonForTimer:(NSTimer *)timer
{
MyButton *button = [timer userInfo];
[button highlight];
[button doStuff];
}