当UISlider停止时如何触发方法?

时间:2014-06-10 16:40:27

标签: ios objective-c uislider

我有一个允许用户更改值的UISlider。当滑块从左向右移动时,我希望UILabel不断更新。

所以,我写了这样的UISlider方法:

    - (IBAction)yearsSlider:(UISlider *)sender
{
    self.yearsLabel = [NSString stringWithFormat:@"%.0f", sender.value];

}

这很好用。当用户停止滑块时,我需要触发一个不同的方法。

我考虑过使用NSTimer - 所以重写上面的方法就像这样:

     - (IBAction)yearsSlider:(UISlider *)sender
    {
        self.yearsLabel = [NSString stringWithFormat:@"%.0f", sender.value];

 if (!self.timer){
        self.timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(requestCalculation) userInfo:nil repeats:NO];] 
    }

    }

然后在requestCalculation方法中,我使计时器无效并将其设置为nil =,如此:

 [self.timer invalidate];
self.timer = nil;

这会减慢速度 - 但滑块移动时会调用该方法。这不是我想要的。

我知道我可以使用self.mySlider.continuous = NO;,这意味着当用户将手指从滑块上抬起时,目标方法才会被触发一次。这个问题是我的UILabels没有更新,因为用户在滑块上左右滑动。

3 个答案:

答案 0 :(得分:3)

设置self.mySlider.continuous = YES;,并在与UIControlEventValueChanged对应的方法中更新您的标签。

然后,为事件UIControlEventTouchUpInsideUIControlEventTouchUpOutside添加一个带有不同选择器的方法,并在那里执行(显然很昂贵的)计算。

答案 1 :(得分:2)

您可以使用UIControlEvent UIControlEventTouchUpInside在用户抬起手指时触发操作(也许您需要检查触摸取消并在外面触摸)

[self.mySlider addTarget:self action:@selector(_ended) forControlEvents: UIControlEventTouchUpInside];

答案 2 :(得分:2)

你有正确的想法。但是你用错误的方法取消了计时器。您想要取消yearsSlider:方法中的(上一个)计时器,而不是requestCalculation方法。

- (IBAction)yearsSlider:(UISlider *)sender {
    // Cancel the current timer
    [self.timer invalidate];

    self.yearsLabel = [NSString stringWithFormat:@"%.0f", sender.value];

    // Start a new timer in case this is the last slider value
    self.timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(requestCalculation) userInfo:nil repeats:NO];
}
BTW - 这次检查似乎是一个相当长的延迟。较小的东西可能会更好。

请勿使requestCalculation中的计时器无效。把它设置为零。

仅供参考 - 使用NSNumberFormatter将滑块值转换为用户显示的值。这样做可确保为用户的区域设置正确格式化值。