1

I am trying to increase a variable's value while uibutton is kept pressing. But when user leaves button, increasing of variable's value will be stopped.

i have tried using threads with touch down and touchupinside but couldn't make it work.

-(void) changeValueOfDepthFields:(UIButton *)sender {
    if (pressing) 
        pressing = NO;
    else 
        pressing = YES;

    pressingTag = 0;

    while (pressing) {

    [NSThread detachNewThreadSelector:@selector(increaseValue) toTarget:self withObject:nil];
    }
}

- (void) stopValueChange:(UIButton *)sender {

    pressing = NO;
}


[fStopUp addTarget:self action:@selector(changeValueOfDepthFields:) forControlEvents:UIControlEventTouchDown];
[fStopUp addTarget:self action:@selector(stopValueChange:) forControlEvents:UIControlEventTouchUpInside];


- (void) increaseValue {

    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    fstopVal = fstopVal + 0.1;

    [self performSelectorOnMainThread:@selector(changeTextOfValues) withObject:nil waitUntilDone:YES];
    [pool release];
}


- (void) changeTextOfValues {
     fStopField.text = [NSString stringWithFormat:@"%.02f", fstopVal];
}

I wonder if there is an alternative way to do this or not. It seems very simple but couldn't think of any other solution than this one.

Atulkumar V. Jain
  • 5,102
  • 9
  • 44
  • 61
gurkan
  • 3,457
  • 4
  • 25
  • 38
  • check below function. May it will help you rather code that much and let me know if you need any other optimization. – Kuldeep Mar 23 '12 at 13:04
  • You should consider if a "touch and hold" is the correct gesture to be using. iOS users are used to swipe up/down or touch and hold then slide up/down for adjusting values like that rather than touch and hold which is more of a mouse gesture. – Nick Bull Mar 23 '12 at 13:12
  • 2
    see UIStepper. Apple added a "touch and hold" UIControl. It can't be more correct. – Matthias Bauch Mar 23 '12 at 13:17
  • @MatthiasBauch It's always nice to learn something new! Thanks for that. – Nick Bull Mar 23 '12 at 20:15

1 Answers1

2

It is much easier to use an NSTimer.

- (void)changeValueOfDepthFields:(UIButton *)sender
{
    if (!self.timer) {
        self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(increaseValue) userInfo:nil repeats:YES];
    }
}

- (void)stopValueChange:(UIButton *)sender
{
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
}

- (void)increaseValue
{
    fstopVal = fstopVal + 0.1;
    fStopField.text = [NSString stringWithFormat:@"%.02f", fstopVal];
}

Note: The previous code is just for reference, I didn't do any memory management for example.

sch
  • 27,436
  • 3
  • 68
  • 83