How can I programmatically pause an NSTimer?

前端 未结 15 1744
梦毁少年i
梦毁少年i 2020-11-27 13:06

I\'m using an NSTimer to do some rendering in an OpenGL based iPhone app. I have a modal dialog box that pops up and requests user input. While the user is providing input

15条回答
  •  庸人自扰
    2020-11-27 13:21

    The code below is for use with a scrollview, that brings content on at regular intervals, and loops back to the front on completion, but the same logic can be used for any pause/restart button.

    The timer fires on load (initiateFeatureTimer), and pauses for user-interaction (will begin dragging method), allowing the user to look at content for as long as she likes. When user lifts her finger (will end dragging) the featurePaused boolean is reset, but also, you have the option of adding in a little more of a delay.

    This way, the scroller doesn't move off instantly on finger lift, it's more reactive to the user.

    //set vars, fire first method on load.
    featureDelay = 8; //int
    featureInt = featureDelay-1; //int
    featurePaused = false; //boolean
    
    -(void)initiateFeatureTimer {
        featureTimer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(moveFeatureScroller) userInfo:nil repeats:true];
        [featureTimer fire];
    }
     -(void)moveFeatureScroller {
    
        if (!featurePaused){ //check boolean
            featureInt++;
    
             if (featureInt == featureDelay){
                 featureInt = 0; //reset the feature int
    
                /*//scroll logic
                int nextPage = (featurePage + 1) * w;
                if (featurePage == features.count-1){ nextPage = 0; }
                [featureScroller setContentOffset:CGPointMake(nextPage, 0)]; */          
             }
          }
    }
    
    -(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
        featurePaused = true; //pause the timer
    }
    -(void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {
        featurePaused = false; //restart the timer
        featureInt = -3; //if you want to add an additional delay
    }
    

提交回复
热议问题