How to make a blinking (or flashing) cursor on iphone?

Viewed 13183

I'm trying to create a custom "blinking cursor" in UIKit, I've tried as shown below, having 2 functions that basically keep calling each other until the cursor is hidden. But this leads to a nice infinite recursion... for some reason the functions call each other right away, not each half-second as expected.

I tried returning if the 'finished' parameter is not YES (by uncommenting the 'if (!ok)' line), but that leads to no animation at all...

Any better idea? Did I miss something, is there a much-easier way to make a "blinking cursor"?

- (void)onBlinkIn:(NSString *)animationID finished:(BOOL)ok context:(void *)ctx {
if (cursorView.hidden) return;
//if (!ok) return;
[UIView beginAnimations:nil context:UIGraphicsGetCurrentContext()];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationDuration:0.5f];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(onBlinkOut:finished:context:)];
cursorView.textColor = [UIColor grayColor];
[UIView commitAnimations];
}

- (void)onBlinkOut:(NSString *)animationID finished:(BOOL)ok context:(void *)ctx {
if (cursorView.hidden) return;
[UIView beginAnimations:nil context:UIGraphicsGetCurrentContext()];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationDuration:0.5f];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(onBlinkIn:finished:context:)];
cursorView.textColor = [UIColor clearColor];
[UIView commitAnimations];
}
5 Answers
CAKeyframeAnimation *animation = [CAKeyframeAnimation animation];
animation.keyPath = @"opacity";
animation.values =  @[ @(0.0),@(0.0),@(1.0), @(1.0)];
animation.keyTimes = @[ @(0.001),@(0.49),@(0.50), @(1.0)];
animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
animation.duration = 1.2;
animation.autoreverses = NO;
animation.repeatCount= HUGE;
[layer addAnimation:animation forKey:@"blink"];
Related