0

我试图让按钮在被按下 3 秒时改变颜色。一旦计时器达到第 3 秒,颜色变化是永久性的,但如果用户在时间结束之前释放按钮,则按钮会恢复其原始颜色。到目前为止我所拥有的是:在viewDidLoad

UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]
                                           initWithTarget:self
                                           action:@selector(fireSomeMethod)];
longPress.minimumPressDuration = 3.0;
[self.view addGestureRecognizer:longPress]; 

fireSomeMethod我有

- (void)someMethod {
        [UIView transitionWithView:self.button
                  duration:2.0
                   options:UIViewAnimationOptionCurveEaseIn
                animations:^{
                    self.button.backgroundColor = [UIColor redColor];
                }
                completion:^(BOOL finished) {
                    NSLog(@"animation finished");
                }];
}

这需要我按住按钮 3 秒才能触发动画,而动画本身需要 2 秒才能完成。所需的行为是动画在 longPress 开始时开始,我在 3 秒前释放按钮,一切都恢复到原来的样子。提前感谢您的帮助

4

1 回答 1

2

使用按钮事件无需使用UILongPressGestureRecognizer

为您的按钮执行 2 个操作,一个用于Touch Down,另一个用于Touch Up Inside

像这样

// For `Touch Up Inside`
- (IBAction)btnReleased:(id)sender {
    [timer invalidate];
    NSLog(@"time - %d",timeStarted);
}
// For `Touch Down`
- (IBAction)btnTouchedDown:(id)sender {
    timer = [NSTimer scheduledTimerWithTimeInterval:1.0f
                                     target:self
                                   selector:@selector(_timerFired:)
                                   userInfo:nil
                                    repeats:YES];
    timeStarted = 0;
}

- (void)_timerFired:(NSTimer *)timer {\
    timeStarted++;
}

timer创建 2个 typeNSTimertimeStartedtype 的变量int。触发计时器Touch Down并使其无效Touch Up Inside,并在Touch Up Inside操作方法中获取按钮被按住的总时间。如上面的代码所示

于 2016-10-26T18:05:52.160 回答