0

我需要帮助才能在按钮上设置计时器。现在我有这个代码,

- (IBAction)btnPlaySound:(id)sender {
    CFBundleRef mainBundle = CFBundleGetMainBundle();
    CFURLRef soundFileUrlRef;
    soundFileUrlRef = CFBundleCopyResourceURL(mainBundle, (CFStringRef) @"", CFSTR(""), NULL);
    UInt32 soundID;
    AudioServicesCreateSystemSoundID(soundFileUrlRef, &soundID);
    AudioServicesPlaySystemSound(soundID);
}

我希望用户每 2 秒只能点击一次此按钮,我必须插入一个NSTimer我认为但以哪种方式?

谢谢

4

1 回答 1

1
- (IBAction)buttonPressed:(id)sender
{
    myTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
}

- (void)timerAction
{

    if (myButton.userInteractionEnabled == YES) {
        //do something
    }

    if ([myButton.tag == 0) {
        [myTimer invalidate];
        [myButton setTag:2];
        myButton.userInteractionEnabled = YES;
    }else{
        myButton.userInteractionEnabled = NO;
        int currentTime = myButton.tag;
        int newTime = currentTime - 1;
        [myButton setTag:newTime];
    }

}

为了使上述代码正常工作,您需要声明一个NSTimer名为“myTimer”和一个UIButton“myButton”。您还需要将按钮初始标签设置为“2”。

于 2012-09-14T05:34:32.913 回答