Show Hide UIView Twice Every 5 Seconds Using NSTim

2019-08-27 15:20发布

I have a UIView added to a view controller. I want to make it blink twice every 5 seconds.

The following code makes the UIView blink on and off every 1 second:

-(void) showHideView{
[UIView animateWithDuration:1
                      delay:5
                    options:UIViewAnimationOptionCurveEaseInOut
                 animations:^{
                     self.myview.alpha = 0;
                 }
                 completion:^(BOOL finished){
                     [UIView animateWithDuration:1
                                           delay:5
                                         options:UIViewAnimationOptionCurveEaseInOut
                                      animations:^{
                                          self.myview.alpha = 1;
                                      }
                                      completion:nil
                      ];
                 }
 ];
}

How can I make the UIView blink twice every 5 seconds? (i.e. a pulse of two blinks)

2条回答
三岁会撩人
2楼-- · 2019-08-27 16:12

Since you've flagged this with iOS7, I might suggest keyframe animation:

[UIView animateKeyframesWithDuration:2.5 delay:0.0 options:UIViewKeyframeAnimationOptionRepeat animations:^{
    [UIView addKeyframeWithRelativeStartTime:0.0 relativeDuration:0.25 animations:^{
        self.myview.alpha = 0.0;
    }];

    [UIView addKeyframeWithRelativeStartTime:0.5 relativeDuration:0.25 animations:^{
        self.myview.alpha = 1.0;
    }];
} completion:nil];

Tweak total duration (how often the cycle repeats), the relative start times (a % of the total duration), and the relative duration (again, a % of the total duration) as you see fit.

查看更多
放我归山
3楼-- · 2019-08-27 16:22

Change both of your delays to zero.

Set both durations to 1.25.

Use a timer to call the method every 2.5 seconds.

How do I use NSTimer?

Edit based on comments:

Use this instead:

-(void) showHideView {
    if( self.view.alpha == 1.0 ) alpha = 0.0;
    else alpha = 1.0;
}

- (void)timerCallback {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1.25  * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
    [self showHideView];
});
    // repeat above code for 2.5, 3.75, 5.0
}

Make your timer call timerCallback every 5 seconds.

查看更多
登录 后发表回答