在iphone中按住uibutton时增加一个值

在iphone中按住uibutton时增加一个值,iphone,uibutton,nsthread,Iphone,Uibutton,Nsthread,我试图在按住uibutton的同时增加变量的值。但当用户离开按钮时,变量值的增加将停止 我曾尝试使用触地和触地内线程,但无法使其工作 -(void) changeValueOfDepthFields:(UIButton *)sender { if (pressing) pressing = NO; else pressing = YES; pressingTag = 0; while (pressing) { [N

我试图在按住uibutton的同时增加变量的值。但当用户离开按钮时,变量值的增加将停止

我曾尝试使用触地和触地内线程,但无法使其工作

-(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];
}

我想知道是否有其他方法可以做到这一点。它看起来非常简单,但除了这个解决方案之外,想不出任何其他解决方案。

使用
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];
}

注意:前面的代码仅供参考,例如,我没有做任何内存管理。

检查下面的函数。如果你需要任何其他的优化,它可能会帮助你编码这么多并且让我知道。你应该考虑一下“触摸和保持”是否是正确的手势。iOS用户习惯于向上/向下滑动或按住,然后向上/向下滑动以调整类似的值,而不是按住,这更像是一种鼠标手势。请参阅UIStepper。苹果添加了一个“触摸并保持”UIControl。再正确不过了。@MatthiasBauch学点新东西总是好的!谢谢你。