【问题标题】:increase a value while uibutton is kept pressing in iphone在 iphone 中按住 uibutton 时增加一个值
【发布时间】:2012-03-23 12:49:34
【问题描述】:

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

我曾尝试使用带有 touch down 和 touchupinside 的线程,但无法使其工作。

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

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

【问题讨论】:

  • 检查以下功能。希望它可以帮助您编写那么多代码,如果您需要任何其他优化,请告诉我。
  • 您应该考虑“触摸并按住”是否是要使用的正确手势。 iOS 用户习惯于向上/向下滑动或触摸并按住然后向上/向下滑动以调整类似的值,而不是触摸并按住,这更像是一种鼠标手势。
  • 参见 UIStepper。 Apple 添加了“触摸并按住”UIControl。再正确不过了。
  • @MatthiasBauch 学习新东西总是很好!谢谢你。

标签: iphone uibutton nsthread


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-16
    • 2014-01-12
    • 1970-01-01
    • 2020-04-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多