在用户点击按钮ios之前设置一个计时器

时间:2012-09-14 05:27:57

标签: ios uibutton nstimer

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

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

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

由于

1 个答案:

答案 0 :(得分: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];
    }

}

为了使上述代码有效,您需要声明一个名为“myTimer”的NSTimer和一个UIButton“myButton”。您还需要将按钮初始标记设置为“2”。